Android 8.0啟動service報錯:java.lang.RuntimeException和java.lang.IllegalStateException
錯誤信息:
java.lang.RuntimeException: Unable to start receiver cn.edu.zut.broadservice.MyReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=cn.edu.zut.broadservice/.MyService }: app is in background uid UidRecord{b67c471 u0a86 RCVR idle change:uncached procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3388)
at android.app.ActivityThread.access$1200(ActivityThread.java:199)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1661)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=cn.edu.zut.broadservice/.MyService }: app is in background uid UidRecord{b67c471 u0a86 RCVR idle change:uncached procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1577)
at android.app.ContextImpl.startService(ContextImpl.java:1532)
at android.content.ContextWrapper.startService(ContextWrapper.java:664)
at android.content.ContextWrapper.startService(ContextWrapper.java:664)
at cn.edu.zut.broadservice.MyReceiver.onReceive(MyReceiver.java:24)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3379)
at android.app.ActivityThread.access$1200(ActivityThread.java:199)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1661)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
錯誤原因:
- 如果針對 Android 8.0 的應用嘗試在不允許其創建后台服務的情況下使用
startService()
函數,則該函數將引發一個IllegalStateException
。 - 新的
Context.startForegroundService()
函數將啟動一個前台服務。現在,即使應用在后台運行,系統也允許其調用Context.startForegroundService()
。不過,應用必須在創建服務后的五秒內調用該服務的startForeground()
函數。 - 如需了解詳細信息,請參閱后台執行限制。
解決方案:
在 原來啟動service的地方,把startService();替換為下面的代碼。
Intent intent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
並且在service的類里面加入(若加入上面代碼后正常運行可忽略此內容)
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(1,new Notification());
}
參考 :參考地址