How to hook into the Power button in Android?

The existing answers don’t completely answer the question and leave out enough details that they won’t work without more investigation. I’ll share what I’ve learned solving this.

First you need to add the following permission to your manifest file:

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

To handle short and long presses add the following overrides to your activity class:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {
        // Do something here...
        event.startTracking(); // Needed to track long presses
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {
        // Do something here...
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

Note: It is worth noting that onKeyDown() will fire multiple times before onKeyLongPress does so you may want to trigger on onKeyUp() instead or other logic to prevent acting upon a series of onKeyDown() calls when the user is really holding it down.

I think this next part is for Cyanogenmod only. If the PREVENT_POWER_KEY constant is undefined then you should not need it.

To start intercepting the power key you need to set the following flag from your activity:

getWindow().addFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);

To stop intercepting the power key (allowing standard functionality):

getWindow().clearFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);

You can switch back and forth between the two modes repeatedly in your program if you wish.

Leave a Comment