在应用程序启动时,应用程序启动应该执行某些网络任务的服务 . 在针对API级别26后,我的应用程序无法在后台启动Android 8.0上的服务 .
引起:java.lang.IllegalStateException:不允许启动服务Intent {cmp = my.app.tt / com.my.service}:app在后台uid UidRecord {90372b1 u0a136 CEM idle procs:1 seq(0, 0,0)}
据我所知,它与:Background execution limits有关
如果针对Android 8.0的应用程序在不允许创建后台服务的情况下尝试使用该方法,则startService()方法现在会抛出IllegalStateException .
“ in a situation when it isn't permitted " - what it's actually mean?? And how to fix it. I don't want to set my service as "前景”
13 回答
不要在onStartCommand中使用:
只需将其更改为:
它会起作用
是的,那是因为你无法在API 26中在后台启动服务 . 所以你可以在API 26之上启动ForegroundService .
你必须使用
并在处理泄漏时发布通知 .
如果你已经集成了firebase消息传递推送通知,那么,
由于Background Execution Limits,为Android O(Android 8.0)添加新的/更新firebase消息传递依赖项 .
如果需要,升级谷歌播放服务和谷歌存储库 .
Update:
如果您在8.0上运行代码,那么应用程序将崩溃 . 所以在前台启动服务 . 如果低于8.0使用此:
如果高于或高于8.0则使用此:
其他答案都是正确的,但我通常是一个好主意,除非你的应用程序是系统相关的) . 请参阅this answer了解如何在未在Google Play中禁止您的应用的情况下请求退出电池优化 .
您还应该检查接收器中的电池优化是否已关闭,以防止崩溃:
允许的情况是临时白名单,其中后台服务的行为与Android O之前相同 .
资料来源:https://developer.android.com/about/versions/oreo/background.html
换句话说,如果您的后台服务不符合白名单要求,则必须使用新的JobScheduler . 它与后台服务基本相同,但它会定期调用,而不是连续在后台运行 .
如果你're using an IntentService, you can change to a JobIntentService. See @kosev' s answer below .
我得到了解决方案对于8.0之前的设备,您只需使用
startService()
,但对于7.0之后的设备,您必须使用startForgroundService()
. 以下是启动服务的代码示例 .在服务类中,请添加以下代码以获取通知:
其中O是Android版本26 .
希望它能解决
IllegalArgumentException
- The first call method in start app or main activity:
- The Second when close app and firebase push:
}
- The last handle in file:
使用
startForegroundService()
而不是startService()
并且不要忘记在启动服务的5秒内在服务中创建startForeground(1,new Notification());
.如果服务通过扩展
IntentService
在后台线程中运行,则可以将IntentService
替换为JobIntentService
,它是作为Android支持库的一部分提供的使用
JobIntentService
的优点是,它在pre-O设备上表现为IntentService
,在O和更高的设备上,它将其作为一项工作发送JobScheduler
也可用于定期/按需作业 . 但是,请确保处理向后兼容性,因为JobScheduler
API仅可从API 21获得从firebase release notes开始,他们表示对Android O的支持首次在10.2.1中发布(尽管我建议使用最新版本) .
请为android O添加新的firebase消息依赖项
如果需要,升级谷歌播放服务和谷歌存储库 .
我看到很多回复建议只使用ForegroundService . 要使用ForegroundService,必须有与之关联的通知 . 用户将看到此通知 . 根据具体情况,他们可能会对您的应用程序感到恼火并将其卸载 .
最简单的解决方案是使用名为WorkManager的新架构组件 . 你可以在这里查看文档:https://developer.android.com/topic/libraries/architecture/workmanager/
您只需定义扩展Worker的工作类 .
然后安排何时运行它 .
简单!您可以通过多种方式配置工作人员 . 它支持重复性工作,如果需要,您甚至可以执行链接等复杂操作 . 希望这可以帮助 .
最好的方法是使用JobIntentService,它使用新的JobScheduler for Oreo或旧服务(如果不可用) .
在你的清单中声明:
在您的服务中,您必须使用onHandleWork替换onHandleIntent:
然后你开始服务: