0

I need the short press power button to not do anything (doesn't lock the screen or turn the light off) just to appear an icon in the corner of my application screen.

Have tried some codes but they work if i long press the power button.

Any ideeas ?

Vlad.mir
  • 685
  • 1
  • 10
  • 28

1 Answers1

0

Permission:

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

Use this code:

@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);
}

onKeyDown will fire several times before the longPress event will fire, therefore you need to set a flag for isFired

Taken from here: How to hook into the Power button in Android?

Community
  • 1
  • 1
mapodev
  • 988
  • 8
  • 14