Android 8.0 还对特定函数做出了以下变更:
如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException。新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。如需了解详细信息,请参阅后台执行限制。
我简单重现了下,我是在Activity的onPause()中延时调用启动了启动服务,按home键进入后台,生命周期执行onPause(),我试了下我手机100s就会重现崩溃了
@Override protected void onPause() { super.onPause(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(context, MyService.class); context.startService(intent); } }, 100000); }报错如下,IllegalStateException异常
12-20 17:57:12.526 15250-15250/com.bill.test E/AndroidRuntime: FATAL EXCEPTION: main Process: com.bill.test, PID: 15250 java.lang.IllegalStateException: Not allowed to start service Intent { act=com.bill.test.service.action.task cmp=com.bill.test/com.bill.test.MyService (has extras) }: app is in background uid UidRecord{dd3b2cd u0a159 LAST bg:+1m40s41ms idle change:cached procs:2 seq(0,0,0)} at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1595) at android.app.ContextImpl.startService(ContextImpl.java:1550) at android.content.ContextWrapper.startService(ContextWrapper.java:664) at com.peopledaily.common.statistics.post.MyService$1.run(MyService.java:69) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6863) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)添加完上面代码还会报下面错误,这时还需要调用startForeground
12-20 18:30:05.066 15831-15831/com.bill.test E/AndroidRuntime: FATAL EXCEPTION: main Process: com.bill.test, PID: 15831 android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{5ca9d62 u0 com.bill.test/com.bill.test.MyService} at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1835) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6863) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Google要求在调用startForegroundService之后5s内调用startForeground,我是Service的onCreate中调用的startForeground,如下: @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForeground(0x64, new Notification()); } }