Catch keypress with android

shuwo picture shuwo · Feb 14, 2010 · Viewed 46.7k times · Source

How can i catch a phone keypress with the android SDK? i've been looking around for hours without finding anything..

For example:

In some cases, i want to catch the message when a user presses the "hang up" button on the phone, and then discard the message before it reaches the OS.

Is this possible?

Answer

user238801 picture user238801 · Feb 14, 2010

You can either handle key events from a view or in general for your whole application:

Handle onKey from a View:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
         /* This is a sample for handling the Enter button */
      return true;
    }
    return false;
}

Remember to implement OnKeyListener and to set your listener YourView.setOnKeyListener(this);

The second possibility would be:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     switch (keyCode) {
     case KeyEvent.KEYCODE_MENU:
        /* Sample for handling the Menu button globally */
        return true;
     }
     return false;
} 

You could also ta a look at onKeyUp.

Resource: http://developer.android.com/reference/android/view/View.html

And here you can see a list with all KeyEvents