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