How to hook into the Power button in Android?

On you activity add:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        // do what you want with the power button
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Though... this kind of keys are somehow special... not sure if it can give problems to you.


Solution:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        Intent i = new Intent(this, ActivitySetupMenu.class);
        startActivity(i);
        return true;
    }

    return super.dispatchKeyEvent(event);
}

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.


As mentioned here https://stackoverflow.com/a/15828592/1065357

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(!hasFocus) {
       Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        sendBroadcast(closeDialog);
    }
}

Tags:

Android