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
You can catch the power button event by overriding onKeyDown method
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Log.e("key","long");
/*//disable the system dialog
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);*/
Toast.makeText(getApplicationContext(),"Power",Toast.LENGTH_SHORT).show();
}
return super.onKeyDown(keyCode, event);
}
As my knowledge we can't do this outside activity (such as background service)
Try this :
@Override
public boolean onKeyLongPress( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_POWER ) {
//Handle what you want in long press.
return true;
}
return super.onKeyLongPress( keyCode, event );
}
Add this in Manifest :
<uses-permission android:name="android.permission.DEVICE_POWER" />
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
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 onWindowFocusChanged
method specified in one of the answers below.
The output will show the toast with "Clicked:26" as attached below.
I see many answers trying to hookin to the powerbutton. However, wouldn't it be more easy to listen for the shutdown event? I'm not sure if this fits your need, but it seems like it.
Simply register a Broadcastreceiver to the following action(s):
<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>
Don't forget to add the following permission:
<uses-permission android:name="android.permission.DEVICE_POWER" />
Try this :
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Intent i = new Intent(this, ActivitySetupMenu.class);
startActivity(i);
return true;
}
return super.dispatchKeyEvent(event);
}