在安卓9.0(Pie)中,用户可以通过设置限制您的应用程序进行后台工作。即使应用程序活动完全在前台,如果应用程序被限制在后台,则我们的应用程序在Pie设备上尝试启动前台服务时会出现以下异常。
RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
我们在已启动的服务中调用了startForeground(),但是尝试启动服务时系统日志显示:
system_process W/ActivityManager: Service.startForeground() not allowed due to bg restriction
似乎在按照前台服务的文档步骤操作时,当您的应用程序仍处于前台时,系统拒绝启动前台服务时收到异常是很奇怪的。我还没有找到与此相关的大量文档,但这是否是已记录的行为?并且,是否至少有一种方法让您的应用程序知道它是否已被后台限制,从而不尝试在前台启动服务?
我的服务代码基本上如下所示。我们的目标API是27。
class MyService : Service() {
override fun onCreate() {
super.onCreate()
// create notification
startForeground(NOTIFICATION_ID, notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null || intent.action == null || intent.action == ACTION_STOP) {
quit()
}
doWork()
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
quit()
}
private fun quit() {
stopForeground(true)
stopSelf()
}
companion object {
fun start(context: Context) {
val intent = Intent(context, MyService::class.java)
intent.action = ACTION_START
ContextCompat.startForegroundService(context, intent)
}
fun stop(context: Context) {
val intent = Intent(context, MyService::class.java)
intent.action = ACTION_STOP
ContextCompat.startForegroundService(context, intent)
}
}
}
name
和export="false"
。 - George EllicksonUsageStatsManager.getAppStandbyBucket
,但文档没有提到受限制的用户应用程序。 - George Ellickson