本文介绍了通知与 API 26 兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有看到有关如何将 NotificationCompat 与 Android O 的 Notification Channels

I dont see any information about how to use NotificationCompat with Android O's Notification Channels

我确实看到了一个采用 channelId 的新构造函数,但是如何获取 Compat 通知并在 NotificationChannel 中使用它,因为 createNotificationChannel 需要一个 NotificationChannel对象

I do see a new Constructor that takes a channelId but how to take a Compat notification and use it in a NotificationChannel since createNotificationChannel takes a NotificationChannel object

推荐答案

仅在 API >= 26 时创建 NotificationChannel

Create the NotificationChannel only if API >= 26

public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default",
                                                          "Channel name",
                                                          NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    notificationManager.createNotificationChannel(channel);
}

然后只需使用:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default");

所以您的通知同时适用于 API 26(带通道)和以下(不带).

So your notifications are working with both API 26 (with channel) and below (without).

这篇关于通知与 API 26 兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 17:26