简体   繁体   中英

Is it possible to detect motion when screen is off?

My app simply need to detect any motion of the device while screen is off.

I know that accelerometer is used for this task but it don't work while screen is off in all devices. this is a list of devices http://www.saltwebsites.com/2012/android-accelerometers-screen-off

so is there a way of taking accelerometer sensor data while screen is off that works on all devices?

or is there a way to detect motion using another sensors?

Partial Wake Lock is all you need to access accelerometer readings while the screen is off.

You can use it like this:

private PowerManager.WakeLock mWakeLock;

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
mWakeLock.acquire();

And after you're done, just release the lock:

mWakeLock.release();

If you obtain accelerometer data in a Service , you could simply acquire lock in it's onCreate() and release in onDestroy() .

Yes you can use accelerometer in the background or when screen is off
but you need to hold a WakeLock [Link] to prevent the device from sleeping.

If you need to detect if the device is still or if it started moving again you might be interested in Recognizing the User's Current Activity from Google Services.

After a quick research I found that most of android devices does not send the accelarometer events when the screen is off. To know more about this bug please take a look on here . Also here too.

When the screen is off the CPU goes to sleep and you cannot capture events without taking a partial wakelock. I suggest you to take a partial wakelock when you call the onPause and release it onResume . Be careful with wakelocks they make your phone drain a really big amount of energy, you should manage them carefully.

PS: You have to acquire the wakelock in the onPause method because if you try to call it somewhere else you might not be able to gain it because the CPU may be already shutted down.

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