Notification.Builder(context)不推荐使用Android O(Notification.Builder(context) deprecated Android O)

339 IT屋

Notification.Builder(context)最近在Android O中被弃用了通知频道.

问题:

使用Notification.Builder(context, StringID)而不是Notification.Builder(context)之后,我确实收到了有关我的Android O设备的通知.
但是,在Android 23(M)上进行尝试后,我没有收到通知.我调试了代码,并且一旦调试器在Android 23(M)上到达Notification.Builder(context,StringID)行,它就停止执行.

FIX:

为解决此问题,我使用了if/else条件在Android O设备与其他设备之间进行隔离.

我有以下代码段:

Notification.Builder notificationBuilder;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notificationBuilder = new Notification.Builder(mContext,
            mContext.getResources().getString(R.string.notification_id_channel));
} else {
    notificationBuilder = new Notification.Builder(mContext);
}

Android Studio中的皮棉显示以下弃用行:

在此处输入图片描述

问题:

是否有摆脱这种过时警告线的方法?

解决方案

您的解决方案是使用NotificationCompat.Builder(Context context, String channelId).如果使用此方法,则不必检查API级别,Builder会忽略Oreo之前的设备上的通道ID.

我已经在API 15、22、23和26上对其进行了测试,并且效果很好.

Notification.Builder(context) has been deprecated recently with the venue of Notification Channels in Android O.

PROBLEM:

After using Notification.Builder(context, StringID) instead of Notification.Builder(context)I did receive a notification to my Android O device.
However, after trying that on an Android 23 (M), I did not receive a notification. I debugged my code and it just stopped executing once the debugger hit the line post Notification.Builder(context, StringID) on Android 23 (M).

FIX:

To Fix this issue, I used if/else condition to segregate between Android O devices and the rest of other devices.

I have the following code snippet:

Notification.Builder notificationBuilder;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notificationBuilder = new Notification.Builder(mContext,
            mContext.getResources().getString(R.string.notification_id_channel));
} else {
    notificationBuilder = new Notification.Builder(mContext);
}

Lint in Android Studio is displaying the following deprecation line:

enter image description here

QUESTION:

Is there a way to get rid off that deprecation warning line?

解决方案

Your solution is to use NotificationCompat.Builder(Context context, String channelId). If you use this you don't have to check the API level, the Builder ignores the channel ID on pre-Oreo devices.

I have tested it on API 15, 22, 23, and 26 and it works perfectly.

本文地址:IT屋 » Notification.Builder(context)不推荐使用Android O

相关文章: