android - Notification not showing in Oreo

ID : 20071

viewed : 12

Tags : androidandroid-notificationsandroid-8.0-oreoandroid

Top 5 Answer for android - Notification not showing in Oreo

vote vote

95

In Android O it's a must to use a channel with your Notification Builder

below is a sample code :

// Sets an ID for the notification, so it can be updated. int notifyID = 1;  String CHANNEL_ID = "my_channel_01";// The id of the channel.  CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel. int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance); // Create a notification and set the notification channel. Notification notification = new Notification.Builder(MainActivity.this)             .setContentTitle("New Message")             .setContentText("You've received new messages.")             .setSmallIcon(R.drawable.ic_notify_status)             .setChannelId(CHANNEL_ID)             .build(); 

Or with Handling compatibility by:

NotificationCompat notification =         new NotificationCompat.Builder(this)         .setSmallIcon(R.drawable.notification_icon)         .setContentTitle("My notification")         .setContentText("Hello World!")         .setChannelId(CHANNEL_ID).build(); 

Now make it notify

NotificationManager mNotificationManager =             (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  mNotificationManager.createNotificationChannel(mChannel);  // Issue the notification. mNotificationManager.notify(notifyID , notification); 

or if you want a simple fix then use the following code:

NotificationManager mNotificationManager =             (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {        mNotificationManager.createNotificationChannel(mChannel);     } 

Updates: NotificationCompat.Builder reference

NotificationCompat.Builder(Context context) 

This constructor was deprecated in API level 26.0.0 so you should use

Builder(Context context, String channelId) 

so no need to setChannelId with the new constructor.

And you should use the latest of AppCompat library currently 26.0.2

compile "com.android.support:appcompat-v7:26.0.+" 

Source from Android Developers Channel on Youtube

Also, you could check official Android Docs

vote vote

90

Here i post some quick solution function with intent handling

public void showNotification(Context context, String title, String body, Intent intent) {     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);      int notificationId = 1;     String channelId = "channel-01";     String channelName = "Channel Name";     int importance = NotificationManager.IMPORTANCE_HIGH;      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {         NotificationChannel mChannel = new NotificationChannel(                 channelId, channelName, importance);         notificationManager.createNotificationChannel(mChannel);     }      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)             .setSmallIcon(R.mipmap.ic_launcher)             .setContentTitle(title)             .setContentText(body);      TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);     stackBuilder.addNextIntent(intent);     PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(             0,             PendingIntent.FLAG_UPDATE_CURRENT     );     mBuilder.setContentIntent(resultPendingIntent);      notificationManager.notify(notificationId, mBuilder.build()); } 
vote vote

77

In addition to this answer, you need to create the notification channel before it can be used.

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {        /* Create or update. */       NotificationChannel channel = new NotificationChannel("my_channel_01",           "Channel human readable title",            NotificationManager.IMPORTANCE_DEFAULT);       mNotificationManager.createNotificationChannel(channel);   } 

Also you need to use channels only if your targetSdkVersion is 26 or higher.

If you are using NotificationCompat.Builder, you also need to update to the beta version of the support library: https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-beta2 (to be able to call setChannelId on the compat builder).

Be careful as this library update raises minSdkLevel to 14.

vote vote

68

public class MyFirebaseMessagingServices extends FirebaseMessagingService {     private NotificationChannel mChannel;     private NotificationManager notifManager;     @Override     public void onMessageReceived(RemoteMessage remoteMessage) {         if (remoteMessage.getData().size() > 0) {             try {                 JSONObject jsonObject = new JSONObject(remoteMessage.getData());                 displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));             } catch (JSONException e) {                 e.printStackTrace();             }         }     }      private void displayCustomNotificationForOrders(String title, String description) {         if (notifManager == null) {             notifManager = (NotificationManager) getSystemService                     (Context.NOTIFICATION_SERVICE);         }         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {             NotificationCompat.Builder builder;             Intent intent = new Intent(this, Dashboard.class);             intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);             PendingIntent pendingIntent;             int importance = NotificationManager.IMPORTANCE_HIGH;             if (mChannel == null) {                 mChannel = new NotificationChannel                         ("0", title, importance);                 mChannel.setDescription(description);                 mChannel.enableVibration(true);                 notifManager.createNotificationChannel(mChannel);             }             builder = new NotificationCompat.Builder(this, "0");              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |                     Intent.FLAG_ACTIVITY_SINGLE_TOP);             pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);             builder.setContentTitle(title)                       .setSmallIcon(getNotificationIcon()) // required                     .setContentText(description)  // required                     .setDefaults(Notification.DEFAULT_ALL)                     .setAutoCancel(true)                     .setLargeIcon(BitmapFactory.decodeResource                             (getResources(), R.mipmap.logo))                     .setBadgeIconType(R.mipmap.logo)                     .setContentIntent(pendingIntent)                     .setSound(RingtoneManager.getDefaultUri                             (RingtoneManager.TYPE_NOTIFICATION));             Notification notification = builder.build();             notifManager.notify(0, notification);         } else {              Intent intent = new Intent(this, Dashboard.class);             intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);             PendingIntent pendingIntent = null;              pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);              Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);             NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)                     .setContentTitle(title)                     .setContentText(description)                     .setAutoCancel(true)                     .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))                     .setSound(defaultSoundUri)                     .setSmallIcon(getNotificationIcon())                     .setContentIntent(pendingIntent)                     .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);             notificationManager.notify(1251, notificationBuilder.build());         }     }      private int getNotificationIcon() {         boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);         return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;     } } 
vote vote

51

If you can't get the push notification in 26+ SDK version?

your solution is here:

public static void showNotification(Context context, String title, String messageBody) {          boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();         Log.e(TAG, "User logged in state: " + isLoggedIn);          Intent intent = null;         if (isLoggedIn) {             //goto notification screen             intent = new Intent(context, MainActivity.class);             intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);         } else {             //goto login screen             intent = new Intent(context, LandingActivity.class);         }          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);         PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);          //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);         //Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);          String channel_id = createNotificationChannel(context);          NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)                 .setContentTitle(title)                 .setContentText(messageBody)                 .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))                 /*.setLargeIcon(largeIcon)*/                 .setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)                 .setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))                 .setVibrate(new long[]{1000, 1000})                 .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)                 .setContentIntent(pendingIntent)                 .setPriority(Notification.PRIORITY_HIGH)                 .setAutoCancel(true);          NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);         notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());     }  public static String createNotificationChannel(Context context) {          // NotificationChannels are required for Notifications on O (API 26) and above.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {              // The id of the channel.             String channelId = "Channel_id";              // The user-visible name of the channel.             CharSequence channelName = "Application_name";             // The user-visible description of the channel.             String channelDescription = "Application_name Alert";             int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;             boolean channelEnableVibrate = true; //            int channelLockscreenVisibility = Notification.;              // Initializes NotificationChannel.             NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);             notificationChannel.setDescription(channelDescription);             notificationChannel.enableVibration(channelEnableVibrate); //            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);              // Adds NotificationChannel to system. Attempting to create an existing notification             // channel with its original values performs no operation, so it's safe to perform the             // below sequence.             NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);             assert notificationManager != null;             notificationManager.createNotificationChannel(notificationChannel);              return channelId;         } else {             // Returns null for pre-O (26) devices.             return null;         }     } 

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)

-> Here you will get push notification using channel_id in your device which is consist 26+ SDK version.

-> Because, the NotificationCompat.Builder(context) is deprecated method now you will use an updated version which is having two parameters one is context, other is channel_id.

-> NotificationCompat.Builder(context, channel_id) updated method. try it.

-> In 26+ SDK version of device you will create channel_id every time.

Top 3 video Explaining android - Notification not showing in Oreo

Related QUESTION?