【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
错误提示:
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null
8.0后要加上channel来区分通知,故需要改为如下的写法:
/**
* 设置服务在前台可见
*/
private void startForeground(){
/**
* 通知栏点击跳转的intent
*/
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, new Intent(this, WelcomeActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
/**
* 创建Notification
*/
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(mMusicModel.getName())
.setContentText(mMusicModel.getAuthor())
.setSmallIcon(R.mipmap.logo)
.setContentIntent(pendingIntent)
.build();
}else{
notification = new Notification.Builder(this)
.setContentTitle(mMusicModel.getName())
.setContentText(mMusicModel.getAuthor())
.setSmallIcon(R.mipmap.logo)
.setContentIntent(pendingIntent)
.build();
}
/**
* 设置notification在前台展示
*/
startForeground(NOTIFICATION_ID, notification);
}
来源:oschina
链接:https://my.oschina.net/jenqz/blog/3147931