一.背景
Android 8.0(target=26)的适配中,有一个关于Notification的适配点:8.0开始使用Notification时候,需要指定一个渠道channel,用来将不同的通知类型分类管理,通常我们的代码会如下处理
//service.startForeground()使用Notification
val channelId = "default"
val notification: Notification
val builder = Notification.Builder(service, channelId)
.setContentTitle("")
.setContentText("")
notification = builder.build()
service.startForeground(1, notification)
实现后,在App管理页的Notification页面中,应该可以看到相应的channel
二.问题
可是当我们实际运行后发现,并没有任何channel选项,然后我们打开log,发现在系统进程里有error类的log
system_process E/NotificationService: No Channel found for pkg=com.kotlinapplication, channelId=default, id=-37201, tag=null, opPkg=com.kotlinapplication, callingUid=10075, userId=0, incomingUserId=0, notificationUid=10075, notification=Notification(channel=default pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0xff607d8b vis=PRIVATE)
很显然是没有找到channel
然而,当我们将target升级到27,即8.1后,再用8.1系统的手机运行,问题就更严重了
android.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)
直接产生崩溃了!!!原因还是没有找到channel,当然,当运行在8.0的系统上时,还是会报系统log而不会崩溃
三.原因
-
既然target是26时候不会崩溃,而27的时候会崩溃,我们就会联想到是8.1相关的适配问题
-
既然8.0手机不会崩溃而8.1手机会崩溃,那基本就可以确认