Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting physical Menu key press in Android

Tags:

android

button

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);
    }
}
like image 839
Entropy1024 Avatar asked Nov 21 '10 19:11

Entropy1024


People also ask

How can I tell if my home button is pressed Android?

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.

Which method is called when home button is pressed in Android?

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.

What is my menu key?

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.


2 Answers

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.

like image 82
SK9 Avatar answered Oct 11 '22 13:10

SK9


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);
    }
}
like image 29
mbonness Avatar answered Oct 11 '22 14:10

mbonness