Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service.startForeground() not allowed due to bg restriction

I'm trying to run a foregroundService in android 8 and later. It starts successfully and the foreground sticky notification is showing when app is in foreground or device is not idle. Problem is once device goes idle, Android decide to kill the service showing this log

Stopping service due to app idle

According to docs as long as there is a notification visible to user service should rarely be killed :( Anyway i setup an alarm that fires every 15 minutes and tries to start the service again if its not running but it fails to start foreground service logging following message

Service.startForeground() not allowed due to bg restriction

With some searching on google: I figured it has something to do with android AppOps management. Apparently there is a permission RUN_ANY_IN_BACKGROUND that should be allow but its actually ignore in my case. I check that using

adb shell cmd get package.name RUN_ANY_IN_BACKGROUND

Just for the sake of testing i set it to allow again manually. But after some time when app goes idle OS set it to ignore again and service is stopped again.

Anyway i can check if i'm violating some limitations that force this RUN_ANY_IN_BACKGROUND flag to ignore?

For some context: The service is suppose to detect user's sleep, so it has to run all night long from user's sleep time until wake time. I start service by calling context.startForegroundService(intent) and then in onStartCommand method i call startForeground passing notification. onStartCommand method always return START_REDELIVER_INTENT constant.

like image 902
Zeeshan Tufail Avatar asked Nov 19 '18 03:11

Zeeshan Tufail


1 Answers

I solved this problem with the following action: Settings -> Apps & notifications -> My App -> Battery -> Background restriction

In the Dialog Fragment choose REMOVE in order to remove Background restriction (if it is enabled).

like image 61
billst Avatar answered Oct 11 '22 06:10

billst