3

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).

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
rahulserver
  • 10,411
  • 24
  • 90
  • 164

2 Answers2

3

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

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
0

its called custom Dialog box, you can crate from link and there is property like

 dialog.setCancelable(false);

using this property it should be possible which you want.

Mayur Dabhi
  • 3,607
  • 2
  • 14
  • 25