Is it possible to detect motion when screen is off?

后端 未结 4 408
情深已故
情深已故 2021-01-13 02:24

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

相关标签:
4条回答
  • 2021-01-13 03:00

    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.

    0 讨论(0)
  • 2021-01-13 03:14

    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.

    0 讨论(0)
  • 2021-01-13 03:15

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

    0 讨论(0)
  • 2021-01-13 03:26

    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.

    0 讨论(0)
提交回复
热议问题