Dinesh Thiyagarajan
Dinesh Thiyagarajan

Reputation: 480

Unable to receive onSensorChanged events inside Work Manager when the app is in Background

I have an app which listens to a broadcast and on receiving the broadcast it starts a work manager immediately. the workManager keeps listening to sensor data's like Proximity, Accelerometer and Magnetometer. I'm using a timer to keep the workManager running until certain conditions are satisfied. below is my workManager implementation which implements SensorEventListener

class CustomWorkManager(appContext: Context, private val parameters: WorkerParameters) :
CoroutineWorker(appContext, parameters), SensorEventListener 

I'm getting the sensor data by overriding the onSensorChanged method while the app is in the foreground. the problem is when the app goes into the background (ie. app is closed) and we receive a broadcast the work manager is initiated but i'm not getting events on onSensorChanged method. Now according to the documentation its said that for (API level 28) or higher we will have to listen to sensor data when your app is in the foreground or as part of a foreground service.

So I tried running a workManager with setForeground method, but still i'm unable to get any events for onSensorChanged method if the app is in the background. So is it not possible to get sensor data for API > 28 inside a workManager even if we set setForeground? since its mentioned in the documentation that it's suggested to use foreground service and for Apps that target Android 12 (API level 31) or higher can't start foreground services while running in the background due to the restrictions , except for a few special cases. so we have no other option than to run a work manager and try to listen to sensor data.

So does this mean we won't be able to listen to sensor data (Proximity, Accelerometer, Magnetometer) inside a workManager when the app is in the background ?

If anybody has any insights reg this please help.

Upvotes: 1

Views: 256

Answers (0)

Related Questions