Is it possible to detect motion when screen is off?

心已入冬 提交于 2019-12-01 06:07:06

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.

Gunaseelan

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!