AccessibilityService流程分析
- AccessibilityService开启方式
- AccessibilityService 开启原理
AccessibilityService开启方式
. 在Framework里直接添加对应用app 服务component。
loadSetting(stmt,
Settings.Secure.ACCESSIBILITY_ENABLED,1);
loadSetting(stmt,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
"com.test.app/com.test.app.service.TestService");
. 在system app中动态添加
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
"com.test.app/com.test.app.service.TestService");
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED, 1);
. 通过intent跳转到settings里面手动添加
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(intent, 0);
AccessibilityService 开启原理
Settings界面的初始话会获取所有已安装的apk的无障碍服务并列表展示出来
用户点击开启无障碍其实最终就是通过Setting secure写入对应的acess服务信息
@Override
142 public void onPreferenceToggled(String preferenceKey, boolean enabled) {
143 ComponentName toggledService = ComponentName.unflattenFromString(preferenceKey);
144 logAccessibilityServiceEnabled(toggledService, enabled);
145 if (!enabled) {
146 logDisabledState(toggledService.getPackageName());
147 }
148 AccessibilityUtils.setAccessibilityServiceState(getPrefContext(), toggledService, enabled);
149 }
关于默认开启无障碍服务的尝试
1 直接写入会报错
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "com.fg/com.fg.test.TestAliveAccessibilityService");
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED, "1");
Caused by: java.lang.SecurityException: Permission denial: writing to settings requires:android.permission.WRITE_SECURE_SETTINGS
2 通过权限申请的方式
可以申请成功但是依旧会permission denial
Permission denial: writing to settings requires:android.permission.WRITE_SECURE_SETTINGS
原因:在android 6.0及以后,WRITE_SETTINGS权限的保护等级已经由原来的dangerous升级为signature,这意味着我们的APP需要用系统签名或者成为系统预装软件才能够申请此权限,并且还需要提示用户跳转到修改系统的设置界面去授予此权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(MainActivity.this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 200);
} else {
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "com.fg/com.fg.test.TestAliveAccessibilityService");
Settings.Secure.putString(getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED, "1");
}
}