Detect phone movement when screen is off

2019-04-14 10:11发布

I am developing an application which should detect user movement and when he stops for more than 5 minutes it should sound an alarm. I was able to detect movement with accelerometer but the problem is it doesnt work when the screen is off. I have also tried using partial wakeLock. Re-registering accelerometer doesnt work either (this should be workaround for motorola devices).

Maybe I can do this using GPS and sound an alarm when GPS speed is less than 1m/s for more than 5 minutes but I am not sure if I will receive GPS updates when screen is off.

So I need a solution that will detect user movement even is screen is off on most devices. Any ideas on how to acomplish this?

Thanks in forward

2条回答
Fickle 薄情
2楼-- · 2019-04-14 10:56

You should acquire a partial wake lock for this kind of operation. Use the PowerManager class.

Something like this:

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,  "SensorRead");
lock.acquire();

You need also this permission in the AndroidManifest.xml:

 <uses-permission android:name="android.permission.WAKE_LOCK" />

Is recommendable using lock.release(); when you're done your work.

EDIT:

Also, this article could be useful for you.

查看更多
我只想做你的唯一
3楼-- · 2019-04-14 11:12

partial wake lock this is what you need to access while your screen is off.

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

查看更多
登录 后发表回答