在屏幕上特定的x,y位置调用触摸事件

时间:2018-11-28 07:53:42

标签: java android

使用与 EVA Facial Mouse类似的功能,我什至需要在设备上x,y位置的屏幕上触发触摸。

我在根视图上尝试调度事件,但是它不起作用。当我有一个特定的视图来调度事件时,它可以工作,但就我而言,在运行时我不会将视图放在焦点上。我也尝试从窗口调用输入事件,但这也无济于事。

有人可以提出一种方法来触发我的视图可以收听的屏幕事件吗?

1 个答案:

答案 0 :(得分:0)

With the reference from this discussion。下面定义的函数似乎对我有用:

@SuppressLint("PrivateApi")
    public void createTouch(float x, float y) {
        String methodName = "getInstance";
        Object[] objArr = new Object[0];
        InputManager im = null;
        try {
            im = (InputManager) InputManager.class.getDeclaredMethod(methodName, new Class[0])
                    .invoke(null, objArr);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }

        //Make MotionEvent.obtain() method accessible
        methodName = "obtain";
        try {
            //noinspection RedundantArrayCreation
            MotionEvent.class.getDeclaredMethod(methodName, new Class[0]).setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //Get the reference to injectInputEvent method
        methodName = "injectInputEvent";
        Method injectInputEventMethod = null;
        try {
            //noinspection RedundantArrayCreation
            injectInputEventMethod = InputManager.class
                    .getMethod(methodName, new Class[]{InputEvent.class, Integer.TYPE});
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        long when = SystemClock.uptimeMillis();
        int source = InputDeviceCompat.SOURCE_TOUCHSCREEN;
        float pressure = 1.0f;
        int action = 0;
        @SuppressLint("Recycle")
        MotionEvent event = MotionEvent.obtain(when, when, action, x, y, pressure,
                1.0f, 0, 1.0f, 1.0f, 0, 0);
        event.setSource(source);
        try {
            assert injectInputEventMethod != null;
            //noinspection RedundantArrayCreation,UnnecessaryBoxing
            injectInputEventMethod.invoke(im, new Object[]{event, Integer.valueOf(0)});
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }