Android 8.0以上startForeground()通知崩溃

1,228 阅读2分钟

原通知创建过程:

MyNotificationService中


private int NOTIFYID = 1;
startForeground(NOTIFYID, generateNotification());

// 8.0以下build通知

private Notification generateNotification(){

    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

    mBuilder.setContentTitle("通知标题")//设置通知栏标题

            .setContentText("通知内容")

            .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间

             .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消

             .setOngoing(true)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)

            .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合

             .setSmallIcon(R.drawable.main_icon);//设置通知小ICON

        Notification nm = mBuilder.build();

        return nm;

}

运行在8.0和以上设备时,报:


startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)

对8.0和以上版本采用下方方式创建通知:


@RequiresApi(api = Build.VERSION_CODES.O)

private NotificationgenerateSavePowerNotificationAboveO() {

    NotificationChannel channel =new NotificationChannel(NOTIFICATION_CHANNEL, NOTIFICATION_CHANNEL, IMPORTANCE_LOW);

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (manager !=null) {

manager.createNotificationChannel(channel);

    }

NotificationCompat.Builder notificationBuilder =new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_);

    Notification notification = notificationBuilder

            .setContentTitle("通知标题")//设置通知栏标题

            .setContentText("内容")

            .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间

            .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消

            .setOngoing(true)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)

            .setSmallIcon(R.drawable.main_icon)//设置通知栏图标

            .build();

    return notification;

}