1.官网地址 https://developer.android.com/reference/android/accessibilityservice/AccessibilityService.html
谷歌官网意思是:辅助功能服务只能用于帮助残障人士使用Android设备和应用程序。
- 创建服务类
编写自己的服务类,需要继承AccessibilityService类.其中要实现onAccessibilityEvent(AccessibilityEvent event)及onInterruput()两个重要的方法:
@SuppressLint("Registered")
public class MyAccessibilityService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
int eventType = accessibilityEvent.getEventType();
switch (eventType) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
Log.e("MyAccessibilityService","View被点击了");
Log.e("MyAccessibilityService","我点击了:"+accessibilityEvent.getText());
Log.e("MyAccessibilityService","当前应用的包名是:"+accessibilityEvent.getPackageName()+accessibilityEvent.getClassName());
break;
case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
//界面文字改动
break;
}
//过滤下只需要监听的包名
if ("xxxxx".equals(accessibilityEvent.getClassName().toString())){
openPacket();
Log.e("MyAccessibilityService","当前应用的包名是:"+accessibilityEvent.getPackageName()+"===="+accessibilityEvent.getClassName()+"==="+ accessibilityEvent.getWindowId());
}
}
@Override
public void onInterrupt() {
}
/**
* 模拟点击
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void openPacket() {
AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
if (nodeInfo != null) {
// List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("测试");
List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("xxxxx:id/rl_action");
for (AccessibilityNodeInfo item : list) {
item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
}
}
在 onAccessibilityEvent中做我们需要做的事情比如单击,双击,滑动等等,当我们拦截到是需要监听的应用事件时候,通过AccessibilityNodeInfo 的findAccessibilityNodeInfosByText和findAccessibilityNodeInfosByViewId,来找到需要执行事件的控件findAccessibilityNodeInfosByText就是控件上的tex文本,findAccessibilityNodeInfosByViewId不能直接填写控件id,需要使用
image.png
dumpview 来查看获取到我们要查找的id才行,这里只会显示能debug的程序的进程。
3.xml配置
image.png在res目录下面创建一个xml用来设置AccessibilityService的额外信息
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="true"
android:notificationTimeout="100"
android:description="@string/accessibillity"
/>
4.在AndroidManifest上配置
<service
android:name=".MyAccessibilityService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility"/>
</service>
按照上面的配置就可以执行一个简单的辅助功能了。
网友评论