How can I reliably simulate touch events on Android without root (like Automate and Tasker)?

前端 未结 1 1169
难免孤独
难免孤独 2020-11-28 11:46

How can I reliably simulate touch events on Android (without rooting) from Java outside my app which runs as a background service?

While this question has been asked

相关标签:
1条回答
  • 2020-11-28 12:13

    As suggested, the best way to simulate touch events since Nougat (API 24) is by using an accessibility service and the AccessibilityService#dispatchGesture method.

    Here is how I did to simulate a single tap event.

    // (x, y) in screen coordinates
    private static GestureDescription createClick(float x, float y) {
        // for a single tap a duration of 1 ms is enough
        final int DURATION = 1;
    
        Path clickPath = new Path();
        clickPath.moveTo(x, y);
        GestureDescription.StrokeDescription clickStroke =
                new GestureDescription.StrokeDescription(clickPath, 0, DURATION);
        GestureDescription.Builder clickBuilder = new GestureDescription.Builder();
        clickBuilder.addStroke(clickStroke);
        return clickBuilder.build();
    }
    
    // callback invoked either when the gesture has been completed or cancelled
    callback = new AccessibilityService.GestureResultCallback() {
        @Override
        public void onCompleted(GestureDescription gestureDescription) {
            super.onCompleted(gestureDescription);
            Log.d(TAG, "gesture completed");
        }
    
        @Override
        public void onCancelled(GestureDescription gestureDescription) {
            super.onCancelled(gestureDescription);
            Log.d(TAG, "gesture cancelled");
        }
    };
    
    // accessibilityService: contains a reference to an accessibility service
    // callback: can be null if you don't care about gesture termination
    boolean result = accessibilityService.dispatchGesture(createClick(x, y), callback, null);
    Log.d(TAG, "Gesture dispatched? " + result);
    

    To perform other gestures, you might find useful the code used for testing the AccessibilityService#dispatchGesture implementation.

    0 讨论(0)
提交回复
热议问题