I am using Android Studio Giraffe 2022.3.1 Patch 2 and when I press for instance the power or volume physical button on my physical mobile phone the log is empty. I use two different devices one with Android 12 (Samsung A10 ) and the second with Android 8.
My goal here is to detect the press of the power button so I can save some logs to DB before the power command is executed.
This is the code that I use to detect any press of physical buttons:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int keyPressed = event.getKeyCode();
Log.d("MainActivity","\nonKeyDown" +
"\nkey code: " + keyCode + "" +
"\nevent key pressed: " + keyPressed );
return super.onKeyDown(keyCode, event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyPressed = event.getKeyCode();
Log.d("MainActivity","\ndispatchKeyEvent" +
"\nevent key pressed: " + keyPressed );
return super.dispatchKeyEvent(event);
}
AFAIK, that button press is not sent to apps, but instead is purely handled by the system. The HOME button works similarly.
You are welcome to try to listen to
ACTION_SCREEN_OFFbroadcasts, if you'd like. However...That is not really going to work, in terms of the "before the power command is executed" part. The OS is not going to wait around for a bunch of apps to do arbitrary things before processing that button press.
Also, please bear in mind that prior to Android 14, your process is likely to be terminated just by being in the background. Saving logs until a power button press means that you are going to lose those logs. Instead, save them immediately or perhaps periodically.