I am trying to detect when the physical Menu button on my Android phone has been pressed. I though the code below would work but it does not. Where am I going wrong please?
The error returned is 'Illegal modifier for parameter onKeyDown; only final is permitted'
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// Do Stuff
} else {
return super.onKeyDown(keyCode, event);
}
}
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken a text view.
When you press the Home button on the device, the onPause method will be called. If the device thinks that it needs more memory it might call onStop to let your application shut down. The device can restart your application later from a stopped state.
The Menu key is located to the right of the space bar between the Windows Key and the Ctrl key. In contrast, the Menu key doesn't have a duplicate like the Alt, Ctrl, and Windows key do on both sides of the space bar.
I'd look for an up key event, rather than a down event, with onKeyUp
.
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// ........
return true;
}
return super.onKeyUp(keyCode, event);
}
We return true
because we're handling the event; return false
if you want the system to handle the event too.
You can do all of this in your Activity
instance too because Activity
is a known indirect subclass of KeyEvent
.
Based on all of the above this appears to be the correct implementation that will consume menu key "up" events only and pass on other key events to the superclass.
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// ...
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
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