views:

223

answers:

1

Hello! 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?

+1  A: 

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

Layne
Note that this does not work for all keys. HOME definitely cannot be caught this way, and END_CALL may not -- I forget about that one. Also, if you want to intercept the BACK button, you are better off implementing onBackPressed() in newer Android SDKs, though that does not work on older phones.
CommonsWare
END_CALL also can not be intercepted by the app.Note also that the original poster seems to want to intercept keys before they are delivered to another app, which it outright not possible for any keys.
hackbod
Also not that the hardware END_CALL button doesn't even exist on some phones, like the Motorola Droid and the Nexus One, so doing anything special with this button probably isn't a great idea.
mbaird