代码之家  ›  专栏  ›  技术社区  ›  GuilhermeFGL

通知兼容。Android O中弃用的生成器

  •  182
  • GuilhermeFGL  · 技术社区  · 8 年前

    Android O

    buildToolsVersion "26.0.1"
    

    Android Studio中的Lint显示了一个针对以下通知生成器方法的弃用警告:

    new NotificationCompat.Builder(context)
    

    问题是: 安卓开发者更新文档描述 通知频道

    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

    我的问题是:

    我找到的一个解决方案是在通知中将通道ID作为参数传递。建造商建造商。但这个解决方案并不完全可重用。

    new Notification.Builder(MainActivity.this, "channel_id")
    
    10 回复  |  直到 7 年前
        1
  •  194
  •   Aleksandar G Vicky Vicent    5 年前

    文档中提到,builder方法 NotificationCompat.Builder(Context context) 已被弃用。我们必须使用具有 channelId 参数:

    NotificationCompat.Builder(Context context, String channelId)
    

    NotificationCompat.Builder Documentation:

    此构造函数在API级别26.0.0-beta1中被弃用。请使用 通知必须指定NotificationChannel Id。

    Notification.Builder Documentation:

    此构造函数在API级别26中被弃用。请使用 通知。而不是生成器(上下文、字符串)。全部已发布 通知必须指定NotificationChannel Id。

    ,并将该生成器传递给助手方法,并在该方法中设置首选设置。

        2
  •  121
  •   Aks4125 Kims Sifers    7 年前

    enter image description here

    以下是截至的所有android版本的工作代码 具有向后兼容性。

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

        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
  •  32
  •   Jerry101    8 年前

    调用2-arg构造函数: 有关与Android O的兼容性,请致电support-v4 NotificationCompat.Builder(Context context, String channelId) .在Android N或更早版本上运行时 channelId 将被忽略。在Android O上运行时,还可以创建一个 NotificationChannel 信道ID .

    过期样本代码: Notification.Builder 使命感 new Notification.Builder(mContext) 已过时。

    Notification.Builder(Context context) NotificationCompat.Builder(Context context) 反对支持 Notification[Compat].Builder(Context context, String channelId) Notification.Builder(android.content.Context) NotificationCompat.Builder(Context context) .)

    不推荐的类: 整个班级 NotificationCompat.Builder v7 NotificationCompat.Builder )之前,v7 需要支持 NotificationCompat.MediaStyle NotificationCompat.MediaStyle media-compat library android.support.v4.media 包裹如果你需要的话,用那个 MediaStyle

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

    看见 Recent Support Library Revisions

        4
  •  24
  •   Alexander Farber    7 年前

    而不是检查 Build.VERSION.SDK_INT >= Build.VERSION_CODES.O

    将以下行添加到 application 第节 AndroidManifest.xml Set Up a Firebase Cloud Messaging Client App on Android

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

    然后将带有通道名称的行添加到 文件:

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

    之后,您将能够使用新版本的 NotificationCompat.Builder

    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
  •  21
  •   Arpit    8 年前

    下面是示例代码,它在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());
    
        6
  •  8
  •   Community Mohan Dere    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);
    
        }
    
        7
  •  4
  •   Tim Diekmann suresh madaparthi    7 年前
    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)
    

    一些用户以以下形式使用此代码:

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

        8
  •  2
  •   Zaman    6 年前
    1. 使用该通道ID生成通知。 例如
    
    ...
     public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
    ...
    ...
    NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_ID+"_name",
                    NotificationManager.IMPORTANCE_HIGH);
    
    NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
    notifManager.createNotificationChannel(channel);
    
    
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(getString(R.string.notification_text))
                    .setOngoing(true)
                    .setContentIntent(broadcastIntent)
                    .setSmallIcon(R.drawable.ic_tracker)
                    .setPriority(PRIORITY_HIGH)
                    .setCategory(Notification.CATEGORY_SERVICE);
    
            startForeground(1, builder.build());
    ...
    
    
        9
  •  1
  •   Sandeep Singh    7 年前

    使用NotificationCompat。而不是生成器(上下文、字符串)。所有已发布的通知必须指定NotificationChannel Id。

        10
  •  1
  •   FreddicMatters    4 年前

    我构建了这段代码,允许您向android api级别显示通知;26或api级别>=26

      private void showNotifcation(String title, String body) {
            //Este método muestra notificaciones compatibles con Android Api Level < 26 o >=26
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //Mostrar notificacion en Android Api level >=26
                final String CHANNEL_ID = "HEADS_UP_NOTIFICATIONS";
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID,
                        "MyNotification",
                        NotificationManager.IMPORTANCE_HIGH);
    
                getSystemService(NotificationManager.class).createNotificationChannel(channel);
                Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
                        .setContentTitle(title)
                        .setContentText(body)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setAutoCancel(true);
                NotificationManagerCompat.from(this).notify(1, notification.build());
    
            }else{
                //Mostrar notificación para Android Api Level Menor a 26
                String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                        .setContentTitle(title)
                        .setContentText(body)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setAutoCancel(true);
    
                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(/*notification id*/1, notificationBuilder.build());
    
            }
    
        }
    

    干杯