Android开发中如何模拟输入
作者:可爱的黑精灵 时间:2022-03-02 02:07:18
目录
input 指令
模拟输入
text
keyevent
tap
swipe
主要思路是使用 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");
来源:https://www.cnblogs.com/chenjy1225/p/13158093.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java中异常处理之try和catch代码块的使用
Spring boot 整合Logback过程示例解析
![](https://img.aspxhome.com/file/2023/4/69354_0s.png)
探讨:如何使用委托,匿名方法对集合进行万能排序
通过面试题解析 Java 类加载机制
Java设计模式之接口隔离原则精解
![](https://img.aspxhome.com/file/2023/5/80935_0s.png)
java emoji表情存储的解决方法
Springboot+Netty+Websocket实现消息推送实例
http请求绕过Filter的实现实例
C#中把英文字母转换为大写或小写的方法
基于Java实现收发电子邮件功能
![](https://img.aspxhome.com/file/2023/7/80307_0s.png)
C#实现XML文件操作详解
![](https://img.aspxhome.com/file/2023/0/67050_0s.png)
opencv配置的完整步骤(win10+VS2015+OpenCV3.1.0)
![](https://img.aspxhome.com/file/2023/4/100304_0s.png)
Unity3d实现无限循环滚动背景
Springboot jar主清单属性丢失解决方案
![](https://img.aspxhome.com/file/2023/4/61124_0s.png)
Unity实现枚举类型中文显示
![](https://img.aspxhome.com/file/2023/1/100151_0s.gif)
springboot 整合 sa-token简介及入门教程
![](https://img.aspxhome.com/file/2023/7/83457_0s.png)
HelloSpringMVC注解版实现步骤解析
java String的深入理解
![](https://img.aspxhome.com/file/2023/5/69895_0s.png)
intellij idea创建第一个动态web项目的步骤方法
![](https://img.aspxhome.com/file/2023/7/110607_0s.png)
Spark Streaming算子开发实例
![](https://img.aspxhome.com/file/2023/8/80928_0s.jpg)