关于developer warning for xxx failed to post notification on channel null

3,579 阅读1分钟

这是因为Android8.0之后启动后台服务的更改导致的。

嗯,不啰嗦了,直接贴完整代码吧。

// 这里是适配8.0之后如何启动后台服务
Intent intent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
   context.startForegroundService(intent);
}else { 
   context.startService(intent);
}

下面是service中需要添加的代码,在onStartCommand的回调中添加的


        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //当sdk版本大于26
            String id = "MyService";
            String description = "my-service";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(id, description, importance);
            manager.createNotificationChannel(channel);
            notification = new Notification.Builder(this, id)
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    // 这个icon不管用不用必须加!!!!!
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(true)
                    .build();
            manager.notify(1, notification);
        } else {
            //当sdk版本小于26
            notification = new NotificationCompat.Builder(this)
                    // 这个icon不管用不用必须加!!!!!
                    .setSmallIcon(R.drawable.ic_launcher)
                    .build();
            manager.notify(1, notification);
        }

        startForeground(888, notification);