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

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

虽然之前已经提出过这个问题,但大多数答案都使用了ADB 。 (例如如何模拟Android设备上的触摸事件? )

https://github.com/chetbox/android-mouse-cursor使用辅助function提供了一个很好的解决方案,但不是很可靠,因为并非所有视图都对它做出响应,并且游戏在大多数时间都没有响应。

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

这是https://github.com/chetbox/android-mouse-cursor使用的当前代码。

Android版本是8.0,现货Android

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

如建议的那样,自Nougat(API 24)以来模拟触摸事件的最佳方法是使用辅助function服务和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); 

要执行其他手势,您可能会发现用于测试 AccessibilityService#dispatchGesture实现的代码很有用 。