If you're running a UI Automator test, there are two techniques you can use depending on the device's Android version:
API 21+
If you only target API 18 or higher, than you can just use the shell:
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.executeShellCommand("input text 1234"); // Type '1234'
device.executeShellCommand("input keyevent 66"); // Press the Enter key
API 18+
If you also support API 18-19, then you cannot use the shell because it's not available, and you cannot use instrumentation key injection if you're interacting with an app that's not your own, such as the system UI. Instead, use UiAutomation.injectInputEvent().
Grab an instance of UiAutomation
and store is somewhere:
UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
Then define some helper methods:
private void sendKey(int keyCode) {
sendKeyEvent(keyCode, KeyEvent.ACTION_DOWN);
sendKeyEvent(keyCode, KeyEvent.ACTION_UP);
}
private void sendKeyEvent(int keyCode, int action) {
long downTime = SystemClock.uptimeMillis();
KeyEvent event = new KeyEvent(
downTime,
downTime,
action,
keyCode,
0,
0,
KeyCharacterMap.VIRTUAL_KEYBOARD,
0,
KeyEvent.FLAG_FROM_SYSTEM,
InputDevice.SOURCE_KEYBOARD
);
uiAutomation.injectInputEvent(event, true);
}
Then use it like this:
sendKey(KeyEvent.KEYCODE_1);
sendKey(KeyEvent.KEYCODE_2);
sendKey(KeyEvent.KEYCODE_3);
sendKey(KeyEvent.KEYCODE_4);
sendKey(KeyEvent.KEYCODE_ENTER);