28

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?

4

3 回答 3

44

您的解决方案是使用NotificationCompat.Builder(Context context, String channelId). 如果您使用它,则不必检查 API 级别,生成器会忽略 pre-Oreo 设备上的通道 ID。

我已经在 API 15、22、23 和 26 上对其进行了测试,并且运行良好。

于 2017-08-31T10:53:29.257 回答
3

您必须定义一个唯一的 channelId(例如“MyChannelId_01”)并调用 NotificationCompat.Builder(ctx,“MyChannelId_01”)。构造的通知将发布在此 NotificationChannel“MyChannelId_01”上。

这允许您定义通知的重要性(这控制发布到此频道的中断通知的程度。值是 IMPORTANCE_UNSPECIFIED、IMPORTANCE_NONE、IMPORTANCE_MIN、IMPORTANCE_LOW、IMPORTANCE_DEFAULT 或 IMPORTANCE_HIGH)。

您可以在此处找到示例:创建通知通道

于 2017-08-26T08:14:43.167 回答
2

我遇到了同样的问题,因为我的目标是 android 22 和 24,所以我只是这样做了: NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, "")

我相信有人会说这是一个 hack,但它消除了警告,我没有问题。

似乎传递一个空字符串适用于 < android 26。

也许其他人可以说明这是否会导致 26 出现问题。

谢谢

于 2017-08-14T23:30:25.167 回答