android: 安卓8.0系统notification适配Failed to post notification on channel “null”(转)

本文转自:https://blog.csdn.net/HUandroid/article/details/78972228

刚刚升级了8.0系统后,模拟器突然出现以下错误“Failed to post notification on channel “null””
由于8.0通知栏增加了channel渠道式消息分发机制,在Android文档中编写的:
https://developer.android.com/preview/features/notification-channels.html

所以要去对8.0系统进行适配:

//代码省略
         String name = "my_package_channel";//渠道名字
        String id = "my_package_channel_1"; // 渠道ID
        String description = "my_package_first_channel"; // 渠道解释说明
        PendingIntent pendingIntent;//非紧急意图,可设置可不设置

        if (notificationManager == null) {
           notificationManager =  (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        }
        //判断是否是8.0上设备
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = null;
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, name, importance);
                mChannel.setDescription(description);
                mChannel.enableLights(true); //是否在桌面icon右上角展示小红点
                notificationManager.createNotificationChannel(mChannel);
            }
            notificationBuilder = new NotificationCompat.Builder(this);

            intent = new Intent(this, DownloadService.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

            notificationBuilder.
                    setSmallIcon(R.mipmap.logo)
                    .setContentTitle(app_name)
                    .setContentText(app_name+"正在下载......")
                    //.setContentIntent(pendingIntent)
                    .setChannelId(id)
                    .setAutoCancel(true);
        }else{
            notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.logo)
                    .setContentTitle(app_name)
                    .setContentText(app_name+"正在下载......")
                    .setAutoCancel(true);

        }


        notificationManager.notify(0, notificationBuilder.build());
        //代码省略

完成以上适配基本就没问题了,如果使用了第三方推送的同学,请去更新最新SDK。

参考链接:解决Fail to post notification on channel "null"的方法

 
原文地址:https://www.cnblogs.com/yongdaimi/p/14976858.html