androidnotifications

Android notification is not showing


I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.

I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.

Code of those files:

Notification n = new Notification.Builder(this)
        .setContentTitle("New mail from " + "[email protected]")
        .setContentText("Subject")
        .setContentIntent(pIntent).setAutoCancel(true)
        .setStyle(new Notification.BigTextStyle().bigText(longText))
        .build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected

notificationManager.notify(0, n);

Solution

  • The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:

    .setSmallIcon(R.drawable.icon)
    

    Android Oreo (8.0) and above

    Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.

    NotificationManager mNotificationManager;
    
    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
    Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
    
    NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
    bigText.bigText(verseurl);
    bigText.setBigContentTitle("Today's Bible Verse");
    bigText.setSummaryText("Text in detail");
    
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
    mBuilder.setContentTitle("Your Title");
    mBuilder.setContentText("Your text");
    mBuilder.setPriority(Notification.PRIORITY_MAX);
    mBuilder.setStyle(bigText);
    
    mNotificationManager =
        (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    
    // === Removed some obsoletes
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        String channelId = "Your_channel_id";
        NotificationChannel channel = new NotificationChannel(
                                            channelId,
                                            "Channel human readable title",
                                            NotificationManager.IMPORTANCE_HIGH);
       mNotificationManager.createNotificationChannel(channel);
      mBuilder.setChannelId(channelId);
    }
    
    mNotificationManager.notify(0, mBuilder.build());