AccessibilityService的用法
- 新建一个
android
工程 - 载工程中新建一个
MyService
继承 AccessibilityService
- 载清单文件中加入如下注册
Service
代码
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
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_config" />
</service>
- 在工程的res目录下新建xml目录,并创建文件
accessibility_config.xml
文件内容如下:
<?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=""
android:canRetrieveWindowContent="true"
android:description="@string/accessibility_service_description" // 这里的在String中配置一下就ok,内容自由发挥
android:packageNames="com.android.mms" // 这里配置的是要监听的应用程序的包名
android:notificationTimeout="100" />
- 在
MyService
中实现 onAccessibilityEvent
方法中实现监听当前手机屏幕上的控件信息
@Override
public void onAccessibilityEvent(final AccessibilityEvent event) {
event.getPackageName();
AccessibilityNodeInfo mAccessibilityNodeInfo = getRootInActiveWindow();
getChildView(mAccrssibilityNodeInfo);
}
public void getChildView(AccessibilityNodeInfo root){
if (root == null)
return;
Rect outBounds = new Rect();
root.getBoundsInScreen(outBounds);
Log.d("aaaaaaaaaaaaaaaaaaaaaaaaaaa", outBounds.height() + "-" + outBounds.width() + " : " + root.getText() + root.getClassName());
for (int j = 0; j < root.getChildCount(); j++) {
getChildView(root.getChild(j));
}
}