问题描述:
[JMessageReceiverHelper] MessageReceiver run failed:Not allowed to start service Intent { cmp=com.xxxx.xxxx/.push.NotificationService (has extras) }: app is in background uid UidRecord{e088b1e u0a276 CEM bg:+2m43s723ms idle procs:2 seq(0,0,0)}
解决办法:
使用startForegroundService
在启动服务的地方:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, YourService.class));
} else {
context.startService(new Intent(context, YourService.class));
}
补充:
解决了上述问题,以为OK了,但是但是……又出现了新的问题,当APP在前台时,收到消息后崩溃了o(╥﹏╥)o,报了如下异常:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxx.xxxx, PID: 8707
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{a2a7125 u0 com.xxx.xxxx/.push.NotificationService}
查阅大神博客得知系统创建服务后,应用有5秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。
解决办法就是在使用了
context.startForegroundService(intent);启动服务后,在service的 onStartCommand()中调用 startFortForeground().
startForeground