Update: I got curious about this. Take a look at the android.view.View source code: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View.java
a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.
code:
/**
* Handle a key event before it is processed by any input method
* associated with the view hierarchy. This can be used to intercept
* key events in special situations before the IME consumes them; a
* typical example would be handling the BACK key to update the application's
* UI instead of allowing the IME to see it and close itself.
*
* @param keyCode The value in event.getKeyCode().
* @param event Description of the key event.
* @return If you handled the event, return true. If you want to allow the
* event to be handled by the next receiver, return false.
*/
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return false;
}
Using dispatchKeyEvent:
@Override
public boolean dispatchKeyEvent (KeyEvent event) {
Log.d("**dispatchKeyEvent**", Integer.toString(event.getAction()));
Log.d("**dispatchKeyEvent**", Integer.toString(event.getKeyCode()));
if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
Toast.makeText(this, "Back button pressed", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
Logs the two events independently even for the back key. The only key that did not log was KEYCODE_HOME
, for some reason. In fact, if you maintain the back button pressed, you will see several ACTION_DOWN
(0) events in a row (and much more if you return false;
instead). Tested in an Eclair emulator and a Samsung Captivate (custom Froyo ROM).