Skip to content

Instantly share code, notes, and snippets.

@anddam
Last active December 6, 2021 06:02
Show Gist options
  • Save anddam/7276579 to your computer and use it in GitHub Desktop.
Save anddam/7276579 to your computer and use it in GitHub Desktop.
Programmatically dispatch KeyEvent
KeyEvent powerKeyUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_POWER);
KeyEvent powerKeyDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);
powerKeyDown = powerKeyDown.changeTimeRepeat(powerKeyDown, SystemClock.uptimeMillis() - 100, 1);
dispatchKeyEvent(powerKeyDown);
if (dispatchKeyEvent(powerKeyUp))
Log.d("PML", "The event was consumed in dispatchKeyEvent() ACTION_UP");
else
Log.d("PML", "The event was NOT consumed in dispatchKeyEvent() ACTION_UP");
//// this is an alternate way of dispatching the long press key event using KeyEvent.DispatcherState
// KeyEvent.DispatcherState powerKeyState = new KeyEvent.DispatcherState();
// powerKeyState.performedLongPress(powerKeyDown);
// powerKeyDown.dispatch(this, powerKeyState, this);
// *** actual output:
// The event was NOT consumed in dispatchKeyEvent() ACTION_UP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment