android 7.0中引入新的手势api,它在
AccessibilityService中实现
public final boolean dispatchGesture(@NonNull GestureDescription gesture,
@Nullable GestureResultCallback callback,
@Nullable Handler handler)
要使用它很简单,首先声明一个Path:
Path path = new Path(); path.moveTo(100, 500); //点击(100,500)做为起点 path.lineTo(800,500); //水平向右滑动到(800,500)
再创建一个GestureDescription,添加上面的路径,最多可以添加10个路径,实现多段滑动
GestureDescription.Builder builder = new GestureDescription.Builder();
GestureDescription description = builder.addStroke(
new GestureDescription.StrokeDescription(path, 20L, 1000L)).build();
boolean ret=mAccService.dispatchGesture(description,
new AccessibilityService.GestureResultCallback() {
@Override
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
Log.d(TAG,"滑动成功");
}
@Override
public void onCancelled(GestureDescription gestureDescription) {
super.onCancelled(gestureDescription);
Log.d(TAG,"滑动失败 ");
}
}, null);
Log.d(TAG,"滑动:"+ret);
这里碰到个坑,以前没用过这个手势,导致运行后总是掉用 onCancelled,每次都打印 "滑动失败 ",但是 ret 却都返回true,找了很久,才发现是accessibility-service的XML中要加描述android:canPerformGestures="true"
我的XML是这样:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeViewClicked|typeViewFocused|typeWindowStateChanged|typeViewScrolled"
android:accessibilityFeedbackType="feedbackGeneric"
android:description="@string/access_server_description"
android:canRetrieveWindowContent="true"
android:canPerformGestures="true"
android:notificationTimeout="1000" />