Android inject input events 注入Touch 点(x, y) 触摸输入事件
16lz
2021-01-23
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需要
权限,并且跨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/
更多相关文章
- Android Service Bind启动调用service方法
- 【移动安全】Android App Smail代码动态跟踪调试方法
- Android方法过多MutiDex使用说明
- 修改 android 手机 hosts 文件的方法
- android 中 LocalSocket的基本使用方法
- android 取消标题 程序意外停解决方法
- Android删除Alarm的方法
- Android小项目之欢迎滑动页面(最简洁方法)