首页 文章

在Android O中不推荐使用NotificationCompat.Builder

提问于
浏览
99

将我的项目升级到 Android O

buildToolsVersion "26.0.1"

Android Studio中的Lint显示以下通知构建器方法的已弃用警告:

new NotificationCompat.Builder(context)

The problem is: Android开发者更新了描述 NotificationChannel 的文档以支持Android O中的通知,并为我们提供了一个代码段,但使用了相同的弃用警告:

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: 是否还有其他建筑通知解决方案,仍然支持Android O?

我找到的解决方案是将通道ID作为Notification.Builder构造函数中的参数传递 . 但是这个解决方案并不完全可以重用 .

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

8 回答

  • 16

    文档中提到了不推荐使用构建器方法 NotificationCompat.Builder(Context context) . 我们必须使用具有 channelId 参数的构造函数:

    NotificationCompat.Builder(Context context, String channelId)
    

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

    在API级别26.0.0-beta1中不推荐使用此构造函数 . 请改用NotificationCompat.Builder(Context,String) . 所有发布的通知都必须指定NotificationChannel ID .

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

    此构造函数在API级别26中已弃用 . 请改用Notification.Builder(Context,String) . 所有发布的通知都必须指定NotificationChannel ID .

    如果要重用构建器设置器,可以使用channelId创建构建器,并将该构建器传递给辅助方法并在该方法中设置首选设置 .

  • 22

    enter image description here

    这是所有Android版本的工作代码 API LEVEL 26+ 具有向后兼容性 .

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

    更新API 26以设置最高优先级

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

    Call the 2-arg constructor: 为了与Android O兼容,请致电support-v4 NotificationCompat.Builder(Context context, String channelId) . 在Android N或更早版本上运行时,将忽略 channelId . 在Android O上运行时,还要使用相同的 channelId 创建 NotificationChannel .

    Out of date sample code: 几个JavaDoc页面上的示例代码(如Notification.Builder,调用 new Notification.Builder(mContext) )已过期 .

    Deprecated constructors: Notification.Builder(Context context)v4 NotificationCompat.Builder(Context context) 已弃用,有利于 Notification[Compat].Builder(Context context, String channelId) . (见Notification.Builder(android.content.Context)和v4 NotificationCompat.Builder(Context context) . )

    Deprecated class: 不推荐使用整个类 v7 NotificationCompat.Builder . (见v7 NotificationCompat.Builder . )以前,需要v7 NotificationCompat.Builder 来支持 NotificationCompat.MediaStyle . 在Android O中,media-compat libraryandroid.support.v4.media 包中有一个v4 NotificationCompat.MediaStyle . 如果您需要 MediaStyle ,请使用那个 .

    API 14+: 在26.0.0及更高版本的Support Library中,support-v4和support-v7软件包都支持最低API级别14. v#名称是历史名称 .

    Recent Support Library Revisions .

  • 11

    而不是像许多答案那样检查 Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ,而是有一种稍微简单的方法 -

    将以下行添加到 AndroidManifest.xml 文件的 application 部分,如Set Up a Firebase Cloud Messaging Client App on Android doc中所述:

    <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id" 
            android:value="@string/default_notification_channel_id" />
    

    然后在 values/strings.xml 文件中添加一个带有通道名称的行:

    <string name="default_notification_channel_id">default</string>
    

    之后,您将能够使用带有2个参数的NotificationCompat.Builder构造函数的新版本(因为在Android Oreo中已弃用具有1个参数的旧构造函数):

    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());
    }
    
  • 1

    以下是示例代码,它在Android Oreo中运行,而且比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());
    
  • 5

    简单样本

    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);
    
        }
    
  • 92
    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();
    

    正确的代码是:

    Notification.Builder notification=new Notification.Builder(this)
    

    具有依赖性26.0.1和新的更新依赖性,例如28.0.0 .

    有些用户以下面的形式使用此代码:

    Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.
    

    因此逻辑是您将声明或启动哪个方法,然后右侧的相同方法将用于分配 . 如果在Leftside中=你将使用某种方法,那么同样的方法将在=右侧用于新的分配 .

    试试这个代码......一定会有用

  • 78

    在API级别26.1.0中不推荐使用此构造函数 . 请改用NotificationCompat.Builder(Context,String) . 所有发布的通知都必须指定NotificationChannel ID .

相关问题