I'm creating an application that needs to detect the biggest acceleration that the phone detects. Currently it works, but it does not continue the task when the screen turns off. To achieve what I have now, I wrote in onCreate:
mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)
I have initialized these variables globally in the class. I then have implemented onSensorChanged(), onResume(), onPause() and left onAccuracyChanged empty.
From what I have understood implementing functions like this is different than more simply creating an asynchronous task. How would I go about changing this so to make it work in the background as well? Thank you!
You won't be able to use the Sensors API when the app went to the background even with WakeLock - the official documentation is clear about that.
You can easily proceed with using Sensors API even with the phone screen disabled inside a foreground service, though. In order to do that use this documentation as a start - Foreground Service. This doesn't guarantee the eternal live of the Service but it will most definitely live longer than an ordinary Service as well as you will have the access to the Sensors API. I am not sure about WakeLock in this case - you will have to try(but I think you won't need it).
Here is a span of answers. Some of them contain sample code and even links to sample projects
Here and here there are neet examples in form of medium articles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With