通知未在奥利奥中显示 [英] Notification not showing in Oreo

查看:40
本文介绍了通知未在奥利奥中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

普通通知生成器不会在 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 中,必须在通知生成器中使用频道

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.+"

来自 Youtube 上的 Android 开发者频道

此外,您可以查看官方 Android 文档

这篇关于通知未在奥利奥中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆