Android 模拟键盘输出

文章的背景是在获取到红外扫码头扫码上报后的数据后,将对应的数据输出到对应输入框中,数据中可能带回车换行,思路是在后台服务中进行的此操作。

系统模拟键盘输入事件有多种方式:

1. 使用adb指令

进入adb shell 输入input查看指令帮助

k61v1_64_bsp:/ $ input
input
Usage: 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)

模拟键盘输入可以使用如下指令:

adb shell input keyevent keycode      #keycode表示对应键值(例如:3 --KEYCODE_BACK 表示返回键)

上面的命令就可以给安卓系统输入对应的按键,按键名和对应的值对应的表可以自行搜索。

文本输出到输入框可以通过如下指令:

adb shell input text hello

此命令可以在焦点在输入框时,直接输入文本hello。值得注意的是,输入的文本不能带空格,不能是中文。

甚至还可以使用如下指令模拟点击屏幕:

adb shell input tap x y      #x,y表示在屏幕上的坐标

以上指令为测试指令,可以快速的对模拟键盘输入进行测试,那最终还是要以代码的形式呈现,那就要涉及到接下来的另一种方式了

2. 使用Instrumentation

使用key事件进行输入

此方式类似于上面的input keyevent指令,使用代码如下

Instrumentation instrumentation = new Instrumentation();
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);  //测试回车键

注意,此方式必须在子线程中进行操作

使用触摸事件进行输入

此方式类似于上面的input tap指令,使用代码如下

Instrumentation instrumentation = new Instrumentation();
final long eventTime= SystemClock.uptimeMillis();
int action = MotionEvent.ACTION_DOWN;
float x = 720;
float y = 1344;
MotionEvent clickDown = MotionEvent.obtain(eventTime,eventTime,action,x,y,0);
instrumentation.sendPointerSync(clickDown);
action = MotionEvent.ACTION_UP;
MotionEvent clickUp = MotionEvent.obtain(eventTime,eventTime,action,x,y,0);
instrumentation.sendPointerSync(clickUp);

注意,此方式也必须在子线程中进行操作,有些需求就必须使用此方式进行输入,用上面的方式无效,不知道是否为应用做了特殊处理。

其实Tap点击事件在系统源码中可以进行查看,代码路径:
frameworks/base/services/core/java/com/android/server/input/InputShellCommand.java

private void sendTap(int inputSource, float x, float y, int displayId) {
    final long now = SystemClock.uptimeMillis();
    injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, now, now, x, y, 1.0f,
                displayId);
    injectMotionEvent(inputSource, MotionEvent.ACTION_UP, now, now, x, y, 0.0f, displayId);
}

到此,就先写到这里,做下简单的记录,希望对大家起到帮助,有问题可以一起探讨,欢迎指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值