Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

devicemotion doesn't seem to register when device is locked

I have the following code which gives a beep when the (mobile) device is nudged slightly:

let audio = new Audio('ack.mp3');

function handleMotionEvent(event) {
  let x = event.accelerationIncludingGravity.x;
  let y = event.accelerationIncludingGravity.y;    

  if (Math.abs(x) + Math.abs(y) > 2.2) {
    audio.play();
  }
}

window.addEventListener("devicemotion", handleMotionEvent, true);

It works fine, but not at all when the device is locked. Is there any way I can detect this while the device is locked?

like image 565
Dara Java Avatar asked Jun 29 '18 21:06

Dara Java


1 Answers

Seems you have to acquire a partial wake lock for that operation with. PowerManager class.

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,  "SensorRead");
lock.acquire();
window.addEventListener("devicemotion", handleMotionEvent, true);

You need also this permission in the AndroidManifest.xml:

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

More Info

like image 189
UdayaLakmal Avatar answered Oct 20 '22 00:10

UdayaLakmal