Android8.0 启动后台Service问题

 android P上应用在后台启动service时报了个异常:

java.lang.IllegalStateException,Not allowed to start service Intent

Android 8.0 对特定函数做出了以下变更:

  • 如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException
  • 新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。

解决方法就很简单了,把Service启动的逻辑块改为:

if (Build.VERSION.SDK_INT >= 26) {
    context.startForegroundService(intent);
} else {
    // Pre-O behavior.
    context.startService(intent);
}

有个简写:ContextCompat.startForegroundService(context, intent)
因为我不想让用户在控制面板看到通知栏,我没有在创建服务后的五秒内调用startForeground()。我马上试了一下,果然没有了“已停止运行”,但是日志爆出了另一个ANR的错误,虽然不是在主线程,也没有弹窗,但毕竟是个错误,我想一探究竟。

回到官方的描述:在被启动的Service创建服务后的五秒内调用startForground(0, new Notification()),如果不调用或调用时间超过5秒会抛出一个ANR。
果不其然,我只有调用了,这样更好,有前台进程,系统想杀都杀不掉了。

但仔细看一下官方文档,你会发现,官方推荐使用JobScheduler,这是api25的新特性。

参考

https://www.jianshu.com/p/6ce99e03080f

https://blog.csdn.net/magicbaby810/article/details/78791762

猜你喜欢

转载自blog.csdn.net/ws6013480777777/article/details/86477405