1、无障碍服务声明 AndroidManifest.xml
<application>
<service
android:name=".app.MyAccessibilityService"
android:label="My Accessibility Service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:exported="true"
android:enabled="true"
> <!-- 或 android:exported="false" -->
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service_config" />
</service>
</application>
2、无障碍服务设置
<meta-data>引用的xml配置文件,它是应用程序资源目录(<project_dir>/res/xml/accessibility_service_config.xml)中创建的。代码示例:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:packageNames="com.android.permissioncontroller"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canPerformGestures="true"
android:notificationTimeout="100"/>
<!--android:settingsActivity="com.example.myapp/.SettingsActivity" />-->
<!--android:accessibilityFlags="flagDefault"-->
<!--android:packageNames="com.iflytek.speechcloud"-->
3、无障碍服务代码
package com.example.xxx;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
public class MyAccessibilityService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
// 处理无障碍事件,如果需要的话
//Log.d("TAG", "onAccessibilityEvent555555555: "+event);
if(event.getPackageName().equals("com.android.permissioncontroller")){
performClick(928,1650);
Log.d("TAG", "onAccessibilityEvent: 点击执行");
}
}
@Override
public void onInterrupt() {
// 当服务被中断时执行
Log.d("TAG", "onInterrupt: 3333333333");
}
public void performClick(int x, int y) {
// 创建一个点击的路径
Path path = new Path();
path.moveTo(x, y);
// 创建一个手势描述
GestureDescription.Builder builder = new GestureDescription.Builder();
builder.addStroke(new GestureDescription.StrokeDescription(path, 1000, 100));
// 发送手势
GestureDescription gesture = builder.build();
dispatchGesture(gesture, null, null);
}
}