问题描述
我在 Android O 操作系统上使用 Service
类.
I am using Service
Class on the Android O OS.
我打算在后台使用Service
.
如果您的应用面向 API 级别 26 或更高级别,系统会对使用或创建后台服务施加限制,除非应用本身处于前台.如果应用需要创建前台服务,应用应调用startForegroundService()
.
如果使用 startForegroundService()
,Service
会抛出以下错误.
If you use startForegroundService()
, the Service
throws the following error.
Context.startForegroundService() did not then call
Service.startForeground()
这是怎么回事?
推荐答案
来自 Google 在 Android 8.0 行为变化:
From Google's docs on Android 8.0 behavior changes:
即使应用程序在后台,系统也允许应用程序调用 Context.startForegroundService().但是,应用程序必须在服务创建后的五秒内调用该服务的 startForeground() 方法.
解决办法:在 onCreate()
中为您使用的 Service
调用 startForeground()
Context.startForegroundService()
Solution:Call startForeground()
in onCreate()
for the Service
which you use Context.startForegroundService()
另请参阅:后台执行限制,适用于 Android 8.0 (Oreo)
See also: Background Execution Limits for Android 8.0 (Oreo)
这篇关于Context.startForegroundService() 然后没有调用 Service.startForeground()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!