The*_*heo 5 java android accessibilityservice android-8.0-oreo
如何在运行后台服务的应用程序外部从Java可靠地模拟Android上的触摸事件(无需生根)?
尽管以前已经问过这个问题,但是大多数答案都是使用ADB的。(例如如何在Android设备上模拟触摸事件?)
https://github.com/chetbox/android-mouse-cursor使用Accessibility提供了一个很好的解决方案,但是它不是很可靠,因为不是所有视图都响应它,并且游戏在大多数时间都没有响应。
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();
}
Run Code Online (Sandbox Code Playgroud)
Android版本是8.0,库存Android
有没有更好,更可靠的方法来模拟Java中的这些触摸事件?提前致谢!
如所建议的,自牛轧糖(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);
Run Code Online (Sandbox Code Playgroud)
要执行其他手势,您可能会发现用于测试 AccessibilityService#dispatchGesture实现的代码很有用。
| 归档时间: |
|
| 查看次数: |
4329 次 |
| 最近记录: |