NotificationCompat.Builder deprecated in Android O

After upgrading my project to Android O

buildToolsVersion "26.0.1"

Lint in Android Studio is showing a deprecated warning for the follow notification builder method:

new NotificationCompat.Builder(context)

The problem is: Android Developers update their Documentation describing NotificationChannel to support notifications in Android O, and provide us with a snippet, yet with the same deprecated warning:

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

Notifications Overview

My question: Is there is any other solution for building notification, and still support Android O?

A solution I found is to pass the channel ID as a parameter in Notification.Builder constructor. But this solution is not exactly reusable.

new Notification.Builder(MainActivity.this, "channel_id")

回答1:

It is mentioned in the documentation that the builder method NotificationCompat.Builder(Context context) has been deprecated. And we have to use the constructor which has the channelId parameter:

NotificationCompat.Builder(Context context, String channelId)

https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

This constructor was deprecated in API level 26.0.0-beta1. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

https://developer.android.com/reference/android/app/Notification.Builder.html

This constructor was deprecated in API level 26. use Notification.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.

If you want to reuse the builder setters, you can create the builder with the channelId, and pass that builder to a helper method and set your preferred settings in that method.

回答2:

Here is working code for all android version as mentioned in accepted answer.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");        notificationBuilder.setAutoCancel(true)                .setDefaults(Notification.DEFAULT_ALL)                .setWhen(System.currentTimeMillis())                .setSmallIcon(R.drawable.ic_launcher)                .setTicker("Hearty365")                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API                .setContentTitle("Default notification")                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")                .setContentInfo("Info");NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);notificationManager.notify(1, notificationBuilder.build());

UPDATE for API 26 to set Max priority

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);        // Configure the notification channel.        notificationChannel.setDescription("Channel description");        notificationChannel.enableLights(true);        notificationChannel.setLightColor(Color.RED);        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});        notificationChannel.enableVibration(true);        notificationManager.createNotificationChannel(notificationChannel);    }    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);    notificationBuilder.setAutoCancel(true)            .setDefaults(Notification.DEFAULT_ALL)            .setWhen(System.currentTimeMillis())            .setSmallIcon(R.drawable.ic_launcher)            .setTicker("Hearty365")      //    .setPriority(Notification.PRIORITY_MAX)            .setContentTitle("Default notification")            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")            .setContentInfo("Info");    notificationManager.notify(/*notification id*/1, notificationBuilder.build());

回答3:

Call the 2-arg constructor: For compatibility with Android O, call support-v4 NotificationCompat.Builder(Context context, String channelId). When running on Android N or earlier, the channelId will be ignored. When running on Android O, also create a NotificationChannel with the same channelId.

Out of date sample code: The sample code on several JavaDoc pages such as Notification.Builder calling new Notification.Builder(mContext) is out of date.

Deprecated constructors: Notification.Builder(Context context) and v4 NotificationCompat.Builder(Context context) are deprecated in favor of Notification[Compat].Builder(Context context, String channelId). (See Notification.Builder(android.content.Context) and v4 NotificationCompat.Builder(Context context).)

Deprecated class: The entire class v7 NotificationCompat.Builder is deprecated. (See v7 NotificationCompat.Builder.) Previously, v7 NotificationCompat.Builder was needed to support NotificationCompat.MediaStyle. In Android O, there's a v4 NotificationCompat.MediaStyle in the media-compat library's android.support.v4.media package. Use that one if you need MediaStyle.

API 14+: In Support Library from 26.0.0 and higher, the support-v4 and support-v7 packages both support a minimum API level of 14. The v# names are historical.

See Recent Support Library Revisions.

回答4:

Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O as many answers suggest, there is a slightly simpler way -

Add the following line to the application section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:


Then add a line with a channel name to the values/strings.xml file:

default

After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):

private void sendNotification(String title, String body) {    Intent i = new Intent(this, MainActivity.class);    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    PendingIntent pi = PendingIntent.getActivity(this,            0 /* Request code */,            i,            PendingIntent.FLAG_ONE_SHOT);    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);    NotificationCompat.Builder builder = new NotificationCompat.Builder(this,

        getString(R.string.default_notification_channel_id))            .setSmallIcon(R.mipmap.ic_launcher)            .setContentTitle(title)            .setContentText(body)            .setAutoCancel(true)            .setSound(sound)            .setContentIntent(pi);    NotificationManager manager =

        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);    manager.notify(0, builder.build());}

回答5:

Here is the sample code, which is working in Android Oreo and less than Oreo.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);            NotificationCompat.Builder builder = null;            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {                int importance = NotificationManager.IMPORTANCE_DEFAULT;                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);                notificationManager.createNotificationChannel(notificationChannel);                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());            } else {                builder = new NotificationCompat.Builder(getApplicationContext());            }            builder = builder

                    .setSmallIcon(R.drawable.ic_notification_icon)                    .setColor(ContextCompat.getColor(context, R.color.color))                    .setContentTitle(context.getString(R.string.getTitel))                    .setTicker(context.getString(R.string.text))                    .setContentText(message)                    .setDefaults(Notification.DEFAULT_ALL)                    .setAutoCancel(true);            notificationManager.notify(requestCode, builder.build());

回答6:

Simple Sample

    public void showNotification (String from, String notification, Intent intent) {        PendingIntent pendingIntent = PendingIntent.getActivity(                context,                Notification_ID,                intent,                PendingIntent.FLAG_UPDATE_CURRENT

        );        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);            // Configure the notification channel.            notificationChannel.setDescription("Channel description");            notificationChannel.enableLights(true);            notificationChannel.setLightColor(Color.RED);            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});            notificationChannel.enableVibration(true);            notificationManager.createNotificationChannel(notificationChannel);        }        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);        Notification mNotification = builder

                .setContentTitle(from)                .setContentText(notification)//                .setTicker("Hearty365")//                .setContentInfo("Info")                //    .setPriority(Notification.PRIORITY_MAX)                .setContentIntent(pendingIntent)                .setAutoCancel(true)//                .setDefaults(Notification.DEFAULT_ALL)//                .setWhen(System.currentTimeMillis())                .setSmallIcon(R.mipmap.ic_launcher)                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))                .build();        notificationManager.notify(/*notification id*/Notification_ID, mNotification);    }

转载请标明出处:NotificationCompat.Builder deprecated in Android O

文章来源: NotificationCompat.Builder deprecated in Android O

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容