Android inject input events 注入Touch 点(x, y) 触摸输入事件
2016-01-20 17:17
2671 查看
1. 使用Instrumentation
new Thread(new Runnable() { @Override public void run() { Instrumentation mInst = new Instrumentation(); mInst.sendKeyDownUpSync(KeyEvent.KEYCODE_A); //按键事件 mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMilis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, point.x, point.y, 0); //触摸按下 mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMilis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, point.x, point.y, 0); //触摸抬起 } }).start();
查看
sendPointerSync()方法的源码会看到,它使用的是
injectInputEvent()方法实现:
public void sendPointerSync(MotionEvent event) { validateNotAppThread(); if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == 0) { event.setSource(InputDevice.SOURCE_TOUCHSCREEN); } InputManager.getInstance().injectInputEvent(event, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH); }
使用Instrumentation需要
<uses-permission android:name="android.permission.INJECT_EVENTS"/>权限,并且跨App注入事件需要系统应用(AndroidManifest.xml 中加入
android:sharedUserId="android.uid.system")并且平台签名才行。
2. 使用反射直接调用injectInputEvent()
方法:
private void invokeInjectInputEvent(MotionEvent event) { Class cl = InputManager.class; try { Method method = cl.getMethod("getInstance"); Object result = method.invoke(cl); InputManager im = (InputManager) result; method = cl.getMethod("injectInputEvent", InputEvent.class, int.class); method.invoke(im, event, 0); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); }catch (InvocationTargetException e) { e.printStackTrace(); } }
3.使用Runtime.exec 执行
Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); String cmd = "/system/bin/input tap point.x point.y\n"; os.writeBytes(cmd); os.writeBytes("exit\n"); os.flush(); os.close(); process.waitFor();
或者直接:
Runtime.getRuntime().exec(new String[] {"su", "-c", "input tap " + point.x + " " + point.y});
4. 针对特定的应用可以使用Android Accessibility
5. 可以直接使用Adb shell
adb shell input tap point.x point.y
6.monkeyrunner是一个功能更为丰富的选项,不过需要连接电脑
参考链接:1. http://azard.me/blog/2015/06/13/android-cross-app-touch-event-injection/
2. http://blog.csdn.net/mad1989/article/details/38109689
3. http://www.race604.com/android-inject-input-event/
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories