Android 8.0开始Notification 需要指定一个channel,当target大于26时,这个channel需要进行系统注册,否则会crash,crash信息如下:
复制代码
1
2
3
4
5
6
7
8android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=default pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
修改方案
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = "default" val channel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT) val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager nm?.let { if (it.getNotificationChannel(channelId) == null) {//没有创建 it.createNotificationChannel(channel)//则先创建 } } val notification: Notification val builder = Notification.Builder(service, channelId) .setContentTitle("") .setContentText("") notification = builder.build() service.startForeground(FOREGROUND_SERVICE_NOTIFICATION_ID, notification) } private void createNotificationChannel(NotificationManager manager) { if (manager.getNotificationChannel("default") == null) { NotificationChannel notificationChannel = new NotificationChannel("default", "notification_channel", NotificationManager.IMPORTANCE_LOW); notificationChannel.setDescription( "notification_channel_description"); manager.createNotificationChannel(notificationChannel); } }
最后
以上就是安静蜗牛最近收集整理的关于Android Crash:Bad notification for startForeground的全部内容,更多相关Android内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复