How to generate input from adb in Android

This article will introduce how to generate input events including touch and key events from adb command in Android.

1. Adb Command Usage

You can use the input command as follows.

$ adb shell input [<source>] [-d DISPLAY_ID] <command> [<arg>...]

The sources are:
      dpad
      keyboard
      mouse
      touchpad
      gamepad
      touchnavigation
      joystick
      touchscreen
      stylus
      trackball

-d: specify the display ID.
      (Default: -1 for key event, 0 for motion event if not specified.)
The commands and default sources are:
      text <string> (Default: touchscreen)
      keyevent [--longpress] <key code number or name> ... (Default: keyboard)
      tap <x> <y> (Default: touchscreen)
      swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      draganddrop <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll <dx> <dy> (Default: trackball)
      motionevent <DOWN|UP|MOVE> <x> <y> (Default: touchscreen)

2. Generating KeyEvent

In this example, it generates and send a Home key.

In the command, keyevent 3 means to send a KeyEvent corresponding to KeyCode 3 (Home key).

$ adb shell input keyboard keyevent 3

The corresponding key name for the key code can be found at Android Developer - KeyEvent.

For instance, in this site, KEYCODE_HOME is defined as the value 3.

public static final int KEYCODE_HOME
Constant Value: 3 (0x00000003)

public static final int KEYCODE_BACK
Constant Value: 4 (0x00000004)

For another example, If you want to generate KEYCODE_BACK, just enter 4 in the command. then, the event will be sent to the system and then forwarded to the app running in the foreground.

$ adb shell input keyboard keyevent 4

3. Generating MotionEvent (Tap: Short Touch)

The following command create a tap event for the coordinates x=200, y=2200. If you run it, you will see a short touch on those coordinates.

$ adb shell input touchscreen tap 200 2200

4. Generating MotionEvent (Swipe: Touch Down -> Drag -> Up)

The following command generates a swipe event. If you run it, you will see that it touch and drag from x=200, y=2200 to x=200, y=2400.

$ adb shell input touchscreen swipe 200 2200 200 2500

5. Generating MotionEvent (motionevent command)

You can generate motion events close to raw events with motionevent command.

Generally, MotionEvent is composed of ACTION_DOWN, ACTION_MOVE, ACTION_UP in Android.

You can create DOWN, MOVE, UP events in order with the following commands.

$ adb shell input touchscreen motionevent DOWN 200 2200
$ adb shell input touchscreen motionevent MOVE 200 2500
$ adb shell input touchscreen motionevent UP 200 2500

If you run it, you can see the result is almost identical to adb shell input touchscreen swipe 200 2200 200 2500 (except for the time interval between events may be different).

Related Posts

codechachaCopyright ©2019 codechacha