我仅在无法复制的Android 9设备上调查了几个IllegalStateException。首先,我认为这取决于后台启动的限制服务,但是首先,它们是在Android 8中引入的,而在Android 8和2上我没有得到这些异常,第二,stacktrace显示该服务是从onCreate启动的,因此它处于前台,不是吗? ?
完整的堆栈跟踪:
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3430)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2199)
at android.os.Handler.dispatchMessage (Handler.java:112)
at android.os.Looper.loop (Looper.java:216)
at android.app.ActivityThread.main (ActivityThread.java:7625)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)
caused by java.lang.IllegalStateException:
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1810)
at android.app.ContextImpl.startService (ContextImpl.java:1765)
at android.content.ContextWrapper.startService (ContextWrapper.java:664)
at com.max.power.ServiceManager.doStartService (ServiceManager.java:121)
at com.max.power.ServiceManager.start (ServiceManager.java:82)
at com.max.power.ActivityLogin.setupSocketService (ActivityLogin.java:259)
at com.max.power.ActivityLogin.onCreate (ActivityLogin.java:156)
at android.app.Activity.performCreate (Activity.java:7458)
at android.app.Activity.performCreate (Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3409)
行doStartService(ServiceManager.java:121)是:
mActivity.startService(new Intent(mActivity, mServiceClass));
有人能想象那里发生了什么吗?
任何帮助将不胜感激。谢谢!
Intent serviceIntent = new Intent(context,Service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
}
else
{
startService(serviceIntent);
}
“如果您的应用程序的目标是API级别26或更高,除非应用程序本身位于前台,否则系统会限制使用或创建后台服务。如果应用程序需要创建前台服务,则该应用程序应调用startForegroundService()。该方法创建了一个后台服务,但是该方法向系统发出信号,通知该服务会将自己提升到前台。创建该服务后,该服务必须在五秒钟内调用其startForeground()方法。“
[https://stackoverflow.com/a/46138653/11982611回答了为什么可以在Oreo上使用