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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With