通知未在奥利奥(Oreo)中显示 [英] Notification not showing in Oreo
问题描述
Normal Notification Builder在Android O上不显示通知.
Normal Notification Builder doesn't show notifications on Android O.
如何在Android 8 Oreo上显示通知?
How could I show notification on Android 8 Oreo?
是否要添加新的代码以在Android O上显示通知?
Is there any new piece of code to add for showing notification on Android O?
推荐答案
在Android O中,必须在Notification Builder中使用频道
In Android O it's a must to use a channel with your Notification Builder
下面是示例代码:
// 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();
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);
}
更新: NotificationCompat.Builder参考
NotificationCompat.Builder(Context context)
此构造函数在API级别26.0.0中已弃用 所以你应该使用
This constructor was deprecated in API level 26.0.0 so you should use
Builder(Context context, String channelId)
因此无需使用新的构造函数setChannelId
.
so no need to setChannelId
with the new constructor.
您应该使用当前最新的AppCompat库26.0.2
And you should use the latest of AppCompat library currently 26.0.2
compile "com.android.support:appcompat-v7:26.0.+"
此外,您可以查看官方Android文档
这篇关于通知未在奥利奥(Oreo)中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!