Android开发中如何模拟输入

时间:2021-05-20

主要思路是使用 adb shell input指令来模拟按键及触摸输入。

但是前提是需要root,且华为手机出于安全考虑已经停止了root解码。所以测试建议换个别的手机。或是直接用AS中的模拟器,用有Google Apis的版本。

input 指令

我们打开adb,进入shell,输入input可以看到指令的参数说明。

其中source一般都是用的默认值可以忽略,我们主要关注的就是后面的command

  • text:文本输入;keyevent:键盘按键;这两条指令是所有设备通用的。
  • tap:点击屏幕;swipe:滑动屏幕;这两条指令适用于有触摸屏的设备。
  • press,roll适用于有触摸球的设备。

模拟输入

在使用input指令之前我们要先获取一下root权限。

private void execShellCmd(String cmd) { try { Process process = Runtime.getRuntime().exec("su"); OutputStream outputStream = process.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream( outputStream); dataOutputStream.writeBytes(cmd); dataOutputStream.flush(); dataOutputStream.close(); outputStream.close(); } catch (Throwable t) { t.printStackTrace(); } }

text

1.输入之前需要提前获取焦点。
2.输入有特殊含义的特殊字符,无法直接输入 需要使用keyevent 如: ' '

我们整一个EditText,然后进行text输入测试。

execShellCmd("input text 'hello,world'");

我们发现少了一个H,在控制台可以看到日志。

可以看到在按下H的时候,EditText没有获取到焦点。

可能是页面初始化以后就开始执行输入操作,此时editText还没有获取到焦点,获取焦点可能存在点延时。所以我们尝试延迟1s后进行输入。

private Handler handler = new Handler();private Runnable task = new Runnable() { public void run() { execShellCmd("input text 'hello,world'"); }};// 延迟1s后输入handler.postDelayed(task,1000);

keyevent

execShellCmd("input text 'hello,world' \n input keyevent 68 \n input keyevent 21");

输入hello,world,然后输入',然后左移光标

常见的keycode可以参见frameworks/base/core/java/android/view/KeyEvent.java

tap

android 中坐标系如下图所示。

我们可以打开手机中的 开发者选项 -> 指针位置 来辅助定位,可以再上方看到x,y相对的偏移量。

点击屏幕(100,200)位置。

execShellCmd("input tap 100 200");

swipe

滑动屏幕和tap相似只需要传入两个坐标即可。后面也可以设置滑动时间(ms),时间越短滑动的相应距离就会越长。

从屏幕(100,200)滑动到(300,400)。

execShellCmd("input swipe 100 200 300 400");

以上就是Android开发中如何模拟输入的详细内容,更多关于Android 模拟输入的资料请关注其它相关文章!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章