DEV Community

Mayank
Mayank

Posted on

Answer: Android close power off menu programmatically

You can use following code to detect power button press.

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

credits https://stackoverflow.com/a/39197768/9640177

Now to prevent system from showing dialog, you can broadcast to close all…

Top comments (0)