I'm developing an SDK that needs to startForeground service from the background. Because it uses background location and Bluetooth-related works. If the application is killed, the monitoring is performing in the background. That's why I'm using the foreground service. There is a condition that starts the foreground service from the background.
Currently, my SDK using Service to handle this job. But Android 12 on-words it doesn't support to start service from the background.
I'm trying to start the service from the background the below exception throws.
ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false
How can I use WorkManager to fix this issue, all my handling is done by the Service class and how can I pass the Service object to Worker class and start this job inside the Worker class.
Actually, my project is based on beacon technology. and the beacon signals are used to show different recommendations to the user.
In my current implementation, if the application is killed by the user, and also accepts the foreground service, the SDK will be run in the background. and detect the beacon and provide appropriate actions.
My implementation is that, if the application initializes my SDK with the foreground service "OFF" Then sometime later, when the application is in the background and trying to start the foreground service from the background this exception throws. The foreground service-related decisions are held by the server-side API. I'm periodically checking whether the server-side value is changed or not, and if the value is changed the changed action is reflected in the SDK.
Earlier we were using Service
to run background tasks. But, due to Android 12 - Foreground service launch restrictions
, we will not be able to invoke Service
for performing background tasks for Android 12+.
So from now on, from targetSdk 31, Service
can be invoked only when the application is in the foreground. When the application is closed or when the application went to the background, invoking Service
using startForegroundService
will cause ForegroundServiceStartNotAllowedException
.
So to perform background tasks, we need to use Worker
instead of Service
. Please refer to this answer to get an idea of how it is implemented. Hope it helps. Also, refer to the below links to get a high-level overview of what changes needs to be done.