由于Android Oreo,因此当应用程序不在前台时,您将无法启动服务。在我的应用程序中,我以活动的onStart方法启动服务。在大多数情况下,这都可以正常工作。但是,有时会抛出IllegalStateException,它表示应用程序在后台尝试启动服务:
java.lang.IllegalStateException: Not allowed to start service Intent { act=ui cmp=com.someapp/.services.ConnectionService }: app is in background uid UidRecord{8d70361 u0a255 TPSL bg:+3m12s948ms idle change:cached procs:1 proclist:20368, seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1666)
at android.app.ContextImpl.startService(ContextImpl.java:1611)
at android.content.ContextWrapper.startService(ContextWrapper.java:677)
at com.someapp.ui.SomeActivity.connectToBackend(SomeActivity.java:62)
at com.someapp.ui.SomeActivity.onStart(SomeActivity.java:55)
at com.someapp.ui.MainActivity.onStart(MainActivity.kt:228)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
at android.app.Activity.performStart(Activity.java:7348)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3131)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7032)
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:964)
我如下启动服务:
@Override
protected void onStart() {
if (BuildConfig.DEBUG_MODE) Log.d(TAG, "activity started");
super.onStart();
connectToBackend();
}
void connectToBackend() {
Intent intent = new Intent(this, ConnectionService.class);
intent.setAction("ui");
startService(intent);
getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
我注意到只有当我在应用程序中锁定然后解锁手机时,才会发生这种情况。我无法始终如一地复制它。
有人有同样的问题吗?
我正在使用的设备是三星Galaxy S10e。
答案 0 :(得分:-1)
对于牛轧糖后设备,请使用startForegroundService
;对于奥利奥之前的设备,请使用startService
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}