Android8.0 Service使用Notification中发生 Bad notification for startForeground错误
第一步:
启动startService先判断
Intent intent = new Intent(getActivity(), StepService.class);
isBind = getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android8.0以上通过startForegroundService启动service
getActivity().startForegroundService(intent);
} else {
getActivity(). startService(intent);
}
第二步:
解决8.1以上系统开启通知闪退问题:
//进行8.0的判断
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(false);
notificationChannel.setShowBadge(false);//是否显示角标
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
NotificationManager systemService = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
systemService.createNotificationChannel(notificationChannel);
mBuilder.setChannelId(CHANNEL_ONE_ID);
}
Notification notification = mBuilder.build();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
startForeground(notifyId_Step, notification);
**到这里基本就能解决问题了**