奥利奥:在后台调用时,startService()不会引发IllegalStateException [英] Oreo: startService() doesn't throw IllegalStateException when called in background

查看:191
本文介绍了奥利奥:在后台调用时,startService()不会引发IllegalStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Android Oreo中引入的后台执行限制,调用<当应用程序在后台运行时,应使用href ="https://developer.android.com/reference/android/content/Context#startService(android.content.Intent)" rel ="nofollow noreferrer"> startService 抛出IllegalArgumentException.检查以下问题: Android 8.0:java .lang.IllegalStateException:不允许启动服务Intent .

According to the background execution limits introduced in Android Oreo, calling startService when the app is in background should throw an IllegalArgumentException. Check this question: Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent.

我创建了一个针对Android Oreo的示例应用,该应用执行以下操作:

I created a sample app targetting Android Oreo that does the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            startService(new Intent(MainActivity.this, MyService.class));
        }
    }, 5000);
}

然后,我启动应用程序,并在按下主屏幕按钮后立即将应用程序置于后台状态.但是没有抛出异常.怎么会这样?我希望该应用在这种情况下会崩溃.

Then I start the app and after press the home button immediately bringing the app to the background state. But the exception is not thrown. How can it be? I expect the app to crash in this case.

推荐答案

根据Google在后台服务限制:

应用程序位于前台时,它可以自由创建和运行前台和后台服务.当应用进入后台时,它会显示几分钟的窗口,在该窗口中仍可以创建和使用服务.

While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services.

通常,我发现该窗口大约需要一分钟,但是对于其他人来说肯定有所不同.

Generally I've found the window to be something around a minute, but that can certainly be different for others.

使应用程序后台运行并查看类似以下内容后,查看您的总体设备日志(从命令行运行adb logcat或在Android Studio的Logcat窗口中关闭过滤器).

Take a look at your overall device logs (run adb logcat from the command line or turn off filters in Android Studio's Logcat window) after you've backgrounded the app and look for something like:

09-26 13:25:37.150 4741 4756 W ActivityManager:由于应用程序空闲而停止服务:u0a267 -1m12s700ms com.example/.MyService

09-26 13:25:37.150 4741 4756 W ActivityManager: Stopping service due to app idle: u0a267 -1m12s700ms com.example/.MyService

任何在此之后启动服务的请求都应导致异常.我猜想您需要将超时时间延长到一两分钟左右.

Any request to start a service after that should cause the exception. I'm guessing you'll need to up the timeout to something closer to a minute or two.

这篇关于奥利奥:在后台调用时,startService()不会引发IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆