I'm trying to create a foreground service that can keep track of the linear acceleration of the phone, using the Accelerometer sensor. I have a ForegroundService
class that implements Service()
and SensorEventListener
. I have two global variables that I initialize like this:
mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)
I then register the listener, then override onSensorChanged()
, where I should log some values, but nothing is displayed (which means the function does not run at all). Why could this be? Thank you.
Edit: Having done more testing since I've posted the answer, I've noticed that the problem is that Android does not update the values on the Sensors (at least the Linear Acceleration one) when the screen is off. The service clearly keeps running, since other tasks (like the location) do get updates, but the Linear Acceleration sensor stops. Once the screen is turned on again it starts to get updates like it should. How to fix this?