Notification.Builder(context) deprecated Android O

2019-03-22 17:47发布

问题:

This question already has an answer here:

  • NotificationCompat.Builder deprecated in Android O 8 answers

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:

QUESTION:

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

回答1:

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.



回答2:

You have to define a unique channelId (for example "MyChannelId_01") and call NotificationCompat.Builder (ctx, "MyChannelId_01"). The constructed Notification will be posted on this NotificationChannel "MyChannelId_01".

This alow you to define importance of the notification (this controls how interruptive notifications posted to this channel are. Value is IMPORTANCE_UNSPECIFIED, IMPORTANCE_NONE, IMPORTANCE_MIN, IMPORTANCE_LOW, IMPORTANCE_DEFAULT or IMPORTANCE_HIGH).

You can find an example here : Creating a notification channel



回答3:

I had the same issue and since I am targeting android 22 and 24 I just did this: NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, "")

I am sure someone will say this is a hack but it gets rid of the warning and I have no issues.

Seems passing an empty string works for < android 26.

Maybe someone else can state if this causes issues for 26.

Thanks