在onCreate的Application类中,我们具有以下代码:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).isIgnoringBatteryOptimizations(context.getPackageName())) {
final Intent pendingIntent= new Intent(context, ScheduledUpdateService.class);
startService(pendingIntent);
}
}
}
根据Firebase Crashyltics,在“ startService()”行上,我们发生了很多崩溃:
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { ... PairActivityUserId=11 }: app is in background uid UidRecord{3ec0561 u11a247 SVC idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1538)
at android.app.ContextImpl.startService(ContextImpl.java:1484)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at com.myapp.app.MyApplication.onCreate(MyApplication.java:30)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6062)
at android.app.ActivityThread.-wrap1(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
直到现在,它都在不同设备(三星,联想,中兴等)的Android 8和9上发生。 这项检查是否足以从后台开始意图?有提示吗?
答案 0 :(得分:0)
从Android 8开始,如果应用程序在后台运行,则不允许在后台启动服务。 Android要求我们通过content.startForegroundService而不是context.startService显式启动该服务,并且在5秒钟内启动该服务时,必须将其绑定到通知以使其具有UI元素。
如果您每次创建活动时确实需要启动服务,那么您可能会对android.support.v4.app.JobIntentService
这种类型的服务用于在应用程序后台执行简短的任务。
您必须在清单中发布JobIntentService
子类,以便与OS进行交互。它应作为JobService发布,即包含android.permission.BIND_JOB_SERVICE
权限,因为在Android 8和更高版本的平台上,它将以这种方式执行。
<service
android:name=".YourJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
您可以在此处找到有关JobIntentService
的更多信息:
https://developer.android.com/reference/android/support/v4/app/JobIntentService