简体   繁体   中英

How to keep using onSensorChanged() when phone asleep?

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!

Currently it works, but it does not continue the task when the screen turns off.

Sensors events do not get transmitted to apps in the background. And when your screen turns off, that is what happens to your app.

Hence you need to have a service do that work for you and flag that service as a Foreground service.

Here is a link to the documentation about foreground services .

Make sure to read and follow the best practises detailled in the sensor documentation too, they explain there what you are experiencing (on Android 9+) and ways to do it properly on those SDK versions.


Here is a gist that comes up when searching for such info

https://gist.github.com/julian-ramos/6ee7ad8a74ee4b442530


That said, as said in the question comments, this may work for some sensors but not for others. This technique is used with location for instance and works pretty good on most phones. Other sensors may be turned off to save power.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM