##AccessibilityService 无障碍/辅助功能
##使用这个服务需要用户手动授权
Demo:监听当前正在运行的程序
1.创建DetectionService继承 AccessibilityService
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
/*
* 如果 与 DetectionService 相同进程,直接比较 foregroundPackageName 的值即可
* 如果在不同进程,可以利用 Intent 或 bind service 进行通信
*/
foregroundPackageName = event.getPackageName().toString();
/*
* 基于以下还可以做很多事情,比如判断当前界面是否是 Activity,是否系统应用等,
* 与主题无关就不再展开。
*/
ComponentName cName = new ComponentName(event.getPackageName().toString(),
event.getClassName().toString());
}
}
@Override
public void onInterrupt() {
// TODO Auto-generated method stub
}
2.在res文件下创建xml文件,同时创建.xml文件
<?xml version="1.0" encoding="utf-8"?>
<!-- 根据的 Service 的不同功能需要,你可能需要不同的配置 -->
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews" />
3.在配置文件中声明该service。
<service
android:name=".DetectionService"
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>
4.工具方法
/**
* 方法6:使用 Android AccessibilityService 探测窗口变化,跟据系统回传的参数获取 前台对象 的包名与类名
*
* @param packageName 需要检查是否位于栈顶的App的包名
*/
public static String isForegroundPkgViaDetectionService() {
// return packageName.equals(DetectionService.foregroundPackageName);
return DetectionService.foregroundPackageName;
}
5.检测是否开启了‘无障碍、辅助功能’
// 此方法用来判断当前应用的辅助功能服务是否开启
public static boolean isAccessibilitySettingsOn(Context context) {
int accessibilityEnabled = 0;
try {
accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(),
android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
} catch (Settings.SettingNotFoundException e) {
Log.i("URL", "错误信息为:"+e.getMessage());
}
if (accessibilityEnabled == 1) {
String services = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (services != null) {
return services.toLowerCase().contains(context.getPackageName().toLowerCase());
}
}
return false;
}
说明:
<!--accessibilityEventTypes:对那些变化的界面感兴趣:窗口打开、滑动、焦点变化 -->
<!--accessibilityFeedbackType:反馈的类型:语音播放、震动 -->
<!--canRetrieveWindowContent:能否访问活动窗口中的内容 -->
<!--notificationTimeout:接受事件的时间间隔:设置100即可 -->
<!--packageNames:用来监听哪个包产生的事件 -->