Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android close power off menu programmatically

Tags:

java

android

How do I close the Android power menu programmatically? Apps like alarmy are doing it.

I couldn't find out from Android docs as to whether an event listener is there that notifies us of the power menu opened.

Physically, if I click on any region on screen other than the power menu or press back button, the menu gets discmised.

I wonder how can I do this programmatically (I know this is possible, probably via some workaround if not directly via api since alarmy can do it).

like image 948
rahulserver Avatar asked Dec 21 '25 08:12

rahulserver


1 Answers

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 system dialogs.

sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

Complete solution

@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();
 //send broadcast to close all dialogs
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    return true;}
  else
    return super.dispatchKeyEvent(event);
}

If you want to perform a small action just before shutdown, You can do follow this. you can listen for following intent using intent filters.

in your manifest

<uses-permission android:name="android.permission.DEVICE_POWER" />
  ....
  ....//other stuff goes here.

<receiver android:name=".ShutdownReceiver">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
    <action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
  </intent-filter>
</receiver>

credit https://stackoverflow.com/a/39213344/9640177

Once you receive this intent you know that the po

like image 141
mayank1513 Avatar answered Dec 23 '25 22:12

mayank1513



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!