android.app.RemoteServiceException: Bad notification for startForeground

430 阅读1分钟

错误提示:  

    android.app.RemoteServiceException: Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1973)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

  8.0后要加上channel来区分通知,故需要改为如下的写法:

/**
 * 创建Notification
 */
String CHANNEL_ID = "channel_id_01";
String CHANNEL_NAME = "channel_name_test";
int NOTIFICATION_ID = 1;
NotificationChannel notificationChannel;
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notificationChannel = new NotificationChannel(CHANNEL_ID,
            CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.setShowBadge(true);
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(notificationChannel);

    notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setContentIntent(pi)
            .build();
} else {
    notification = new Notification.Builder(this)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setContentIntent(pi)
            .build();
}

/**
 * 设置notification在前台展示
 */
startForeground(NOTIFICATION_ID, notification);