關於developer warning for xxx failed to post notification on channel null

這是由於Android8.0以後啓動後臺服務的更改致使的。bash

嗯,不囉嗦了,直接貼完整代碼吧。ui

// 這裏是適配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的回調中添加的this

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

複製代碼
相關文章
相關標籤/搜索