Android inject input events 注入Touch 点(x, y) 触摸输入事件

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)