原因:AndroidO或者更高的版本为提高设备性能和安全,系统在某些情况下会限制后台服务的创建,如果强制使用startService(intent) 函数,则该函数将引发一个 IllegalStateException,如下:
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: FATAL EXCEPTION: main
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Process: packageName,,,,,,,,,,,,,,,,,,,,,,,,, PID: 3986
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: java.lang.RuntimeException: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=packagename/.servicename (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6555)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=packagename/.servicename (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1522)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startService(ContextImpl.java:1478)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.content.ContextWrapper.startService(ContextWrapper.java:661)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at packageName.ConnectionChangeJobService.onStartJob(ConnectionChangeJobService.java:102)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobService$1.onStartJob(JobService.java:71)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
05-28 17:49:49.693516 3986 3986 E AndroidRuntime: ... 6 more
解决方法:启动服务startService(Intent intent) 函数改用 startForegroundService(Intent intent),服务启动之后 5秒 内要调用startForeground(int id, Notification notification);服务销毁时要调用 stopForeground(int flags);
注意点:
1.startForegroundService(Intent intent),intent 参数必须是显示启动。
2.startForeground(int id, Notification notification),id 不能为0,notification 不能为 null
参考文章:https://blog.csdn.net/sinat_20059415/article/details/80584487