In Android Java/Kotlin development, the equivalent to sending key events via adb shell input keyevent is to use the KeyEvent class and dispatch the event to a view or the system. Here’s how you can achieve this programmatically:
You can simulate key presses using the dispatchKeyEvent method on a View (like an Activity or a View object):
java// Example: Simulate pressing the BACK key KeyEvent backKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); getWindow().getDecorView().dispatchKeyEvent(backKey);
Or in Kotlin:
kotlinval backKey = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK) window.decorView.dispatchKeyEvent(backKey)
Here are some common key codes you might use (equivalent to adb shell input keyevent codes):
KEYCODE_HOMEKEYCODE_BACKKEYCODE_VOLUME_UPKEYCODE_VOLUME_DOWNKEYCODE_POWERKEYCODE_ENTERKEYCODE_DELandroid.permission.INJECT_EVENTS for system-level key injection, which is restricted).adb shell input keyevent), you typically need root access or ADB privileges.javaKeyEvent volumeUp = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP); getWindow().getDecorView().dispatchKeyEvent(volumeUp);
If you need to send key events globally (e.g., for accessibility tools), you can use an AccessibilityService with the performGlobalAction method:
javaAccessibilityService service = ...; // Your AccessibilityService instance service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);