Search code examples
javaandroidevent-handlingkeyboard-eventskeyevent

KeyEventDispatcher - how to separate action key events from Unicode events


I'm implementing a KeyEventDispatcher.dispatchKeyEvent() to pass all keyboard actions to an external (Android) device. One key issue for easily translating KeyEvents to the supplied protocol with the device is to separate the events into two types: Unicode events and "action events" (misc., Editing, navigation keys - F1, Del, Arrows etc.).

Java make it very convenient to tell the Unicode char generated by a user KeyStrokes: You simply check if (KeyEvent)e.getID() == KeyEvent.KEY_TYPED, and e.getKeyChar() is guaranteed to be the generated char. No need to deal with modifier keys, key holds etc.

The problem begins with the other type of key input events, those that do not generate a KEY_TYPED event. As Oracle's documentation for KeyEvent states: "Key combinations which do not result in Unicode characters, such as action keys like F1 and the HELP key, do not generate KEY_TYPED events".

I need to be able to handle these events in two ways:

  • Separate them from KEY_TYPED-generating events, in order to avoid sending duplications of events to the device (i.e. do not send VK_ALT, VK_ENTER etc. if these have already handled as part of a KEY_TYPED event), and,
  • switch the non-KEY_TYPED event over a list of known action events, in order to translate it into a code suitable for the device's protocol.

    Can I achieve either of these? How?


  • Solution

  • OK, that was really easy after all.

    If I only knew there's a KeyEvent.isActionKey() earlier...

    Didn't test all possible cases yet, but it seems to behave just as I expected.