简体   繁体   中英

How to show Android Notifications on screen as well as status bar icon?

I feel like this should be trivial but I can't seem to make a notification show up on the phone's screen - it only shows up in the status bar at the top.

For an example of what I want to do, here's how Facebook Messenger shows up on the screen when you receive a message.

Facebook 屏幕通知

Whenever I send a notification, all it does is show the little icon in the status bar - even if I set the priority to PRIORITY_MAX. Is there another setting I need to do to make it show on screen instead of just status bar?

The Notification display code:

PendingIntent contentIntent = PendingIntent.getActivity(context, nextId++, intent, PendingIntent.FLAG_CANCEL_CURRENT);

Notification.Builder builder = new Notification.Builder(context)
       .setContentTitle(title)
       .setContentText(description)
       .setContentIntent(contentIntent)
       .setSmallIcon(R.drawable.ic_stat_notification)
       .setLargeIcon(largeIcon)
       .setPriority(Notification.PRIORITY_DEFAULT)
       .setAutoCancel(true)
       .setDefaults(Notification.DEFAULT_ALL);

if (android.os.Build.VERSION.SDK_INT >= 21) {
    builder.setColor(context.getResources().getColor(R.color.orange_500))
           .setVisibility(Notification.VISIBILITY_PUBLIC);
}

Notification notification = builder.build();
notificationManager.notify(id, notification);

All things considered, it's a really good idea to use NotificationCompat.Builder over Notification.Builder , let alone creating a Notification manually. It gives you nice backwards compatibility with graceful degradation (all the way back to API Level 4, otherwise known as "gadzooks, that's old"). AFAIK, it's the only way to get some of the Android Wear stuff going, when used in concert with NotificationManagerCompat . And, in this case, it seems to be happier with the newer Android 5.0+ features.

In this case, setPriority(NotificationCompat.PRIORITY_HIGH) on a NotificationCompat.Builder , used with NotificationManagerCompat , will give you the heads-up notification on Android 5.0+.

Another point, make sure the 'importance' of the notification channel you have set up for your notification is set to NotificationManager.IMPORTANCE_HIGH .

This configures how visually intrusive notifications posted to this channel are and 'high' will allow it to peek. If you have this set to NotificationManager.IMPORTANCE_DEFAULT then it won't!

Bear in mind when configuring a notification channel, once the code has ran on your device, you won't be able to alter this again. So if you need to change the importance you will need to uninstall the app and then re-run and you should see the notification on your screen!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM