8.0开始必须给通知设置以一个channelID
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=xxx/0x7f0b0198 vibrate=null sound=null tick defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1782)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6600)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:821)
正确姿势
Notification.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//========================8.0之后要设置通知渠道========================================
String CAHNNEL_ONE_ID = "cn.com.kanjian.audio";
String CAHNNEL_ONE_NAME = "视频课堂";
NotificationChannel channel = new NotificationChannel(CAHNNEL_ONE_ID,CAHNNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(channel);
//=================================================================
builder = new Notification.Builder(AudioPlayService.this,CAHNNEL_ONE_ID);
builder.setOngoing(true)
.setSmallIcon(R.drawable.audio_sound_play)
.setTicker("正在播放:" + StringUtil.formatAudioName(resInfo.audioDetail.audioname))
.setWhen(System.currentTimeMillis())
.setCustomContentView(getRemoteViews(resInfo.audioDetail, isplay, mloadedImage));
// nm.notify(1,builder.build());//一般唤醒通知
}else {
builder = new Notification.Builder(AudioPlayService.this);
builder.setOngoing(true)
.setSmallIcon(R.drawable.audio_sound_play)
.setTicker("正在播放:" + StringUtil.formatAudioName(resInfo.audioDetail.audioname))
.setWhen(System.currentTimeMillis())
.setContent(getRemoteViews(resInfo.audioDetail, isplay, mloadedImage));
}
//开启一个前台服务给通知,保证优先级
startForeground(1, builder.build());
网友评论