这个用到了一个名叫AccessibilityService
的类,这个类是安卓用于开发辅助功能的类。
网上找到一篇文章,对这个类介绍比较详细
android AccessibilityService解析
这里只谈一下如何使用,可以用代码打开关机对话框。对这个类感兴趣的可以看上面那篇文章
首先创建一个Service
继承AccessibilityService
,需要注意的是在AndroidManifest.xml
文件中,需要为这个服务添加android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
和
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
示例:
<service
android:name=".PerformSystemService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
</service>
在合适的地方检查权限(此段代码摘自应用《甜甜圈》):
public boolean isAccessibilitySettingsOn() {
int accessibilityEnabled = 0;
final String service = "你的包名/你的服务的完整地址";
boolean accessibilityFound = false;
try {
accessibilityEnabled = Settings.Secure.getInt(getApplicationContext().getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED);
} catch (Settings.SettingNotFoundException e) {
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
String settingValue = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
splitter.setString(settingValue);
while (splitter.hasNext()) {
String accessabilityService = splitter.next();
if (accessabilityService.equalsIgnoreCase(service)) {
return true;
}
}
}
}
return accessibilityFound;
}
然后如果没有权限的话,跳转到设置中提示用户开启:
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(intent);
最后在你的服务里执行这局代码就OK了
performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);