Why does a physical keyboard's ACTION_DOWN for character keys never reach dispatchKeyEvent/OnKeyListener on an EditText, while ACTION_UP does?


I'm testing hardware keyboard events on a focused EditText. For character keys (e.g. G, keycode 35), only ACTION_UP reaches Activity.dispatchKeyEvent(), the view's OnKeyListener, and onKeyUp(). ACTION_DOWN is logged in onKeyPreIme() but never reaches dispatchKeyEvent(), OnKeyListener, onKeyDown(), or android.text.method.KeyListener.onKeyDown().

class CustomEditText(context: Context) : EditText(context) { override fun onKeyPreIme(keyCode: Int, event: KeyEvent): Boolean { Log.d("Key", "EditText preIme action=${event.action} code=$keyCode") return super.onKeyPreIme(keyCode, event) } override fun dispatchKeyEvent(event: KeyEvent): Boolean { Log.d("Key", "EditText dispatchKeyEvent=${event.action}") return super.dispatchKeyEvent(event) } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { Log.d("Key", "EditText onKeyDown=${event.action}") return super.onKeyDown(keyCode, event) } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { Log.d("Key", "EditText onKeyUp=${event.action}") return super.onKeyUp(keyCode, event) } } // in Activity.onCreate editText.setOnKeyListener { _, keyCode, event -> when (event.action) { KeyEvent.ACTION_DOWN -> Log.d("Key", "DOWN: $keyCode") KeyEvent.ACTION_UP -> Log.d("Key", "UP: $keyCode") } false } // Activity overrides dispatchKeyEvent / onKeyDown / onKeyUp with the same kind of logging

Logcat for pressing and releasing G once (action 0 = DOWN, 1 = UP):

RelativeLayout dispatchKeyEventPreIme=0
Edit Text dispatchKeyEventPreIme=0
Edit Text preIme action=0 code=35
RelativeLayout dispatchKeyEventPreIme=1
Edit Text dispatchKeyEventPreIme=1
Edit Text preIme action=1 code=35
Activity.dispatchKeyEvent
RelativeLayout dispatchKeyEvent=1
Edit Text dispatchKeyEvent=1
UP: 35
Edit Text onKeyUp = 1
Activity.onKeyUp

The DOWN appears only in the pre-IME hooks. No Activity.dispatchKeyEvent, OnKeyListener, onKeyDown, or KeyListener.onKeyDown call follows for it. The character still appears in the field.

Questions:

  1. Is it intended and documented behavior that the IME can consume a hardware key ACTION_DOWN before Activity.dispatchKeyEvent(), so that OnKeyListener and KeyListener.onKeyDown never see it?

  2. Is it IME-specific (does the DOWN reach onKeyDown with another keyboard app), or guaranteed by the framework?

  3. What is the recommended way to receive the DOWN for a focused text field? Is onKeyPreIme the correct hook, or should I use InputType.TYPE_NULL / an InputConnection wrapper?

  4. Is there official documentation describing the IME stage's place in the key-event pipeline?

3
Dec 2 at 10:25 AM
User AvatarRohan Pande
#android#keyboard#android-edittext#keyevent

No answer found for this question yet.