androidkey-events

Android - Why does onKeyUp trigger a KeyEvent, but onKeyDown does not?


In my current View, a keyboard is open with numbers 0 to 9, a delete key and an enter key. I added both an onKeyDown and an onKeyUp event. Both should log the keycode to the debug console when pressed.

@Override
public boolean onKeyDown(int pKeyCode, KeyEvent pKeyEvent) {
    Log.d("KEYDOWN", pKeyCode+"");
    return true; // also tried false
}
@Override
public boolean onKeyUp(int pKeyCode, KeyEvent pKeyEvent) {
    Log.d("KEYUP", pKeyCode+"");
    return true;
}

I pressed every single key on the keyboard with the following result:

D/KEYUP: 8
D/KEYUP: 9
D/KEYUP: 10
D/KEYUP: 11
D/KEYUP: 12
D/KEYUP: 13
D/KEYUP: 14
D/KEYUP: 15
D/KEYUP: 16
D/KEYDOWN: 67
D/KEYUP: 67
D/KEYUP: 7
D/KEYUP: 66

Can someone explain why the keydown event is never triggered for 0-9 and enter? I really need it to trigger when 0-9 are pressed.

EDIT: I added a solution that fixed the issue by replacing both functions with dispatchKeyEvent. This doesn't explain why onKeyDowndidn't recognize those keys, though.

Someone got an answer for this?


Solution

  • I only found a solution to work around this issue, but I did not find the reason WHY this happens in the first place.

    This code did the job:

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction()==KeyEvent.ACTION_DOWN) {
            Log.d("KEYDOWN", event.getKeyCode()+"");
        }
        else if (event.getAction()==KeyEvent.ACTION_UP) {
            Log.d("KEYUP", event.getKeyCode()+"");
        }
        Log.d("KEY", event.getKeyCode()+"");
        return false;
    }