奥利奥中未显示通知

新手上路,请多包涵

普通通知生成器不会在 Android O 上显示通知。

如何在 Android 8 Oreo 上显示通知?

是否有任何新代码要添加以在 Android O 上显示通知?

原文由 amorenew 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

在 Android O 中, 必须在 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();

或通过以下方式处理兼容性:

 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);

或者如果您想要一个简单的修复,请使用以下代码:

 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 中已弃用,因此您应该使用

Builder(Context context, String channelId)

所以不需要 setChannelId 使用新的构造函数。

你应该使用目前最新的 AppCompat 库 26.0.2

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

来自 Youtube 上的 Android 开发者频道

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

原文由 amorenew 发布,翻译遵循 CC BY-SA 4.0 许可协议

我遇到了这个问题,但找到了一个独特的解决方案。

对我来说这是旧代码

String NOTIFICATION_CHANNEL_ID = "com.codedevtech.emplitrack";

工作代码是

String NOTIFICATION_CHANNEL_ID = "emplitrack_channel";

可能是频道 ID 不应包含点“。”

原文由 Harsh Kanjariya 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题