brandall
brandall

Reputation: 6144

Permanent SensorEventListener Shake

I would like to launch an Activity of my application when a shake event is detected. I would like this to happen outside of my application.

There are many great code snippets here and here for example, of how to correctly implement the SensorEventListener, but even if I don't unregister the listener, it still gets destroyed.

How do I prevent it from being destroyed and register a 'permanent' listener? I can't find any such examples anywhere... Any links or guidance would be really appreciated.

Finally, how would I go about only listening for such events when the display is on? I understand that this may be a hardware restriction anyway.

Thanks in advance.

Upvotes: 0

Views: 527

Answers (1)

Dmitry Polishuk
Dmitry Polishuk

Reputation: 119

You can register broadcast receiver for BOOT_COMPLETED intent and in onReceive start your background service with a PARTIAL_WAKELOCK and then register your sensor event listener. Something like this:

@Override
public int onStartCommand(Intent i, int flags, int startId) {
    acquireWakeLock();
    registerSensorListener();
    return START_STICKY;
}

@Override
public void onDestroy() {
    unregisterSensorListener();
    releaseWakeLock();
    super.onDestroy();
}

private void acquireWakeLock() {
    try {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (pm == null) {
            Log.e(TAG, "Power manager not found!");
            return;
        }
        if (wakeLock == null) {
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName());
            if (wakeLock == null) {
                Log.e(TAG, "Could not create wake lock (null).");
                return;
            }
        }
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
            if (!wakeLock.isHeld()) {
                Log.e(TAG, "Could not acquire wake lock.");
            }
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "Caught unexpected exception: " + e.getMessage(), e);
    }
}

private void releaseWakeLock() {
    if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
        wakeLock = null;
    }
}

Hope this helps.

Upvotes: 1

Related Questions