最近终于有时间来整理一下代码 修修bug
然后发现有一样这样的问题,占据了差不多10%的安卓用户,以vivo、OPPO 、荣耀、华为入门机居多。我手上4台机器怎么都复现不出来,真不知道国产厂商做了啥
我们知道 Android 8.0之后规定服务一定要前台显示,不允许直接使用startService,需要用前台方式启动,然后在服务里面在通知栏里搞个通知显示出来,说明服务正在运行。

然后我们看异常信息就这么一句话
Context.startForegroundService() did not then call Service.startForeground()
啥也没了!啥也没了!啥也没了!

就是说调用startForegroundService启动服务,但是没有在服务里面调用startForeground()前台显示(我明明就调用了!竟然说我每调用)
那就搜源码看看,然后发现有两个类似的地方,出现了这句话。但是我这样异常没有冒号也没有ServiceRecord。(知道为什么的小伙伴请务必告诉一下我呗)
不过有冒号的这两种异常日志系统确实也有收集,有很多,估计这日志收集把ServiceRecord这个里面的东西也归类了吧

既然有那就一起看、出现Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord的原因有下面两个
一个是Context.startForegroundService服务启动后没有调用Service.startForeground(),5秒内 服务执行完毕 服务结束、就产生Crash这个异常

另外一个是Context.startForegroundService启动服务后、5秒后都没有调用Service.startForeground()就爆ANR

看完这两个原因我就很懵逼了。
因为我WelcomeActivity 十分简单 onCreate没啥东西 然后获取了一下权限 就openHome了


判断了一下是否在运行、就直接启动了

然后服务里面就Service.startForeground(),通道我也是每个服务new一个的啊,ID我是一个服务一个ID,启动之前我也通过EventBus把万一有的其他这个AppUpdateService个停止了,理论上不会重复了


然后我们再看详细的崩溃日志

结果还真超过了5秒,有些还10几秒 20几秒 ,然后看回代码发现context.startForegroundService(intent);之后就是隔了5秒以上 服务才执行onCreate 然后再startForeground已经为时已晚
这就有点尴尬了正常测试发现每次都是几十毫秒就执行的,但是日志显示这些手机确实是超过5秒以上才启动的 坑!
所以到此android.app.RemoteServiceException Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord 的原因我已经找到了
至于为什么会这样我还要好好研究一下ams了,因为我服务并没有做什么东西只发了一个请求,欢迎页也是很简单。不过我发现就是这些国产手机,安装更新的时候,原来的服务、activity好像是没有杀死的。然后这里会导致Notification ID重复
总结
1.调用startForeground();的时候ID不要重复
2.调用startForeground();的时候ID不能为零!
3.服务启动后优先调用startForeground();
4.onStartCommand这个东西保活的时候,有写的不好就会产生第一点的重复
5.NotificationChannel这个东西每次要new出来getNotificationChannel可能会不太好
网友评论