I\'ve been reading some posts here on Stackoverflow, and I didn\'t find a good solution, I\'m wondering if it\'s possible to detect when the user long press the power button
This simple solution works:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyPressed = event.getKeyCode();
if(keyPressed==KeyEvent.KEYCODE_POWER){
Log.d("###","Power button long click");
Toast.makeText(MainActivity.this, "Clicked: "+keyPressed, Toast.LENGTH_SHORT).show();
return true;}
else
return super.dispatchKeyEvent(event);
}
If you want to stop system pop-up, use the onWindowFocusChangedmethod specified in one of the answers below.
The output will show the toast with "Clicked:26" as attached below.