Detect phone movement when screen is off

和自甴很熟 提交于 2019-12-22 00:09:42

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28380527/detect-phone-movement-when-screen-is-off

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