AccessibilityService官方简介:
The classes in this package are used for development of accessibility service that provide alternative or augmented feedback to the user.
使用这个类可以开发用于给用户提供替换或者是增强反馈的辅助功能服务。An AccessibilityService runs in the background and receives callbacks by the system when AccessibilityEvents are fired. Such events denote some state transition in the user interface, for example, the focus has changed, a button has been clicked, etc. Such a service can optionally request the capability for querying the content of the active window. Development of an accessibility service requires extends this class and implements its abstract methods.
一个AccessibilityService在后台运行并接收系统AccessibilityEvents事件的回调,当用户界面的状态发生改变时会触发AccessibilityEvents事件,例如焦点的变化,点击一个按钮。这个服务可以获取到活动窗口的内容,开发一个辅助功能服务需要继承AccessibilityService并实现其中的抽象方法。An AccessibilityServiceInfo describes an AccessibilityServiceInfo. The system notifies an AccessibilityService for AccessibilityEvents according to the information encapsulated in this class.
一个AccessibilityService有一个用于描述AccessibilityService的AccessibilityServiceInfo对象,系统会通知AccessibilityService根据AccessibilityServiceInfo把信息装进AccessibilityEvents中。
继承AccessibilityService并实现其中的抽象方法。
下面是我Service类:
public class MyService extends AccessibilityService {
private int code = INSTALL;
private static final int INSTALL = 0;
private static final int NEXT = 1;
private static final int FINISH = 2;
/**
* 页面变化回调事件
* @param event event.getEventType() 当前事件的类型;
* event.getClassName() 当前类的名称;
* event.getSource() 当前页面中的节点信息;
* event.getPackageName() 事件源所在的包名
*/
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
// 事件页面节点信息不为空
if (event.getSource() != null) {
// 判断事件页面所在的包名,这里是自己
if (event.getPackageName().equals(getApplicationContext().getPackageName())) {
switch (code) {
case INSTALL:
click(event, "安装", TextView.class.getName());
Log.d("test=======", "安装");
code = NEXT;
break;
case NEXT:
click(event, "下一步", Button.class.getName());
Log.d("test=======", "下一步");
code = FINISH;
break;
case FINISH:
click(event, "完成", TextView.class.getName());
Log.d("test=======", "完成");
code = INSTALL;
break;
default:
break;
}
}
} else {
Log.d("test=====", "the source = null");
}
}
/**
* 模拟点击
* @param event 事件
* @param text 按钮文字
* @param widgetType 按钮类型,如android.widget.Button,android.widget.TextView
*/
private void click(AccessibilityEvent event, String text, String widgetType) {
// 事件页面节点信息不为空
if (event.getSource() != null) {
// 根据Text搜索所有符合条件的节点, 模糊搜索方式; 还可以通过ID来精确搜索findAccessibilityNodeInfosByViewId
List<AccessibilityNodeInfo> stop_nodes = event.getSource().findAccessibilityNodeInfosByText(text);
// 遍历节点
if (stop_nodes !=