- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如何在我作为后台服务运行的应用程序之外,通过 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/
我是一名优秀的程序员,十分优秀!