- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
根据background execution limits在 Android Oreo 中引入,调用 startService当应用程序在后台时应该抛出一个 IllegalArgumentException
。检查这个问题:Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent .
我创建了一个针对 Android Oreo 的示例应用,它执行以下操作:
@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);
}
然后我启动应用程序并在按下主页按钮后立即将应用程序置于后台状态。但不会抛出异常。怎么会这样?我希望应用程序在这种情况下会崩溃。
最佳答案
根据 Google 关于 background service limitations 的文档:
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.
一般来说,我发现这个窗口大约是一分钟,但对于其他人来说肯定会有所不同。
在您将应用设置为后台后,查看您的整体设备日志(从命令行运行 adb logcat
或关闭 Android Studio 的 Logcat 窗口中的过滤器)并查找类似以下内容:
09-26 13:25:37.150 4741 4756 W ActivityManager: Stopping service due to app idle: u0a267 -1m12s700ms com.example/.MyService
在此之后启动服务的任何请求都应该导致异常。我猜您需要将超时设置为接近一两分钟。
关于android - 奥利奥 : startService() doesn't throw IllegalStateException when called in background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316856/
我是一名优秀的程序员,十分优秀!