java - 如何在没有 root 的情况下可靠地模拟 Android 上的触摸事件(如 Automate 和 Tasker)?

标签 java android android-8.0-oreo accessibilityservice

如何在我作为后台服务运行的应用程序之外,通过 Java 可靠地模拟 Android 上的触摸事件(无需 root)?

虽然之前有人问过这个问题,但大多数答案都使用 ADB。 (例如 How to simulate touch events on Android device? )

https://github.com/chetbox/android-mouse-cursor使用辅助功能提供了一个很好的解决方案,但不是很可靠,因为并非所有 View 都响应它,而且游戏在大多数情况下根本不响应。

private void click() {
  AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
  if (nodeInfo == null) return;

  AccessibilityNodeInfo nearestNodeToMouse = findSmallestNodeAtPoint(nodeInfo, cursorLayout.x, cursorLayout.y + 50);

  if (nearestNodeToMouse != null) {
    logNodeHierachy(nearestNodeToMouse, 0);
    nearestNodeToMouse.performAction(AccessibilityNodeInfo.ACTION_CLICK);
  }

  nodeInfo.recycle();
}

This is the current code used by https://github.com/chetbox/android-mouse-cursor.

安卓版本为8.0,原装安卓

是否有更好、更可靠的方法从 Java 模拟这些触摸事件?提前致谢!

最佳答案

如建议的那样,自 Nougat (API 24) 以来模拟触摸事件的最佳方法是使用无障碍服务和 AccessibilityService#dispatchGesture方法。

下面是我如何模拟单击事件。

// (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);

要执行其他手势,您可能会发现 code used for testing 很有用AccessibilityService#dispatchGesture 实现。

编辑:我将博客中的一篇文章与 introduction to Android accessibility services 链接起来.

关于java - 如何在没有 root 的情况下可靠地模拟 Android 上的触摸事件(如 Automate 和 Tasker)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775698/

相关文章:

android - 如何使用数据绑定(bind)创建焦点更改监听器

Android 计算 scrollTo 在 Horizo​​ntalScrollView 中的位置

android - 服务中的前台通知在 Android 8.1 中不起作用

android - Android 8 上的 INSTALL_FAILED_NO_MATCHING_ABIS 错误

android - 在运行 Oreo 和 Pie 的设备中如何在锁定屏幕上覆盖布局

Java无法访问的代码错误

java - 从 eclipse 中的同一文件夹运行不同的类

java - 如何在Java args中添加文件路径

java - 如何使两个对象变量相互引用?

java - 如何显示 Heads up 通知 android