I would like to programmatically enable/disable Accessibility Services listed under Settings->Accessibility option.
I could start Accessibility Intent like below:
The best you can do is manualy open the accessibilty settings with:
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
and start the intent - you can also do it from the prefernece xml file:
intent android:action="android.settings.ACCESSIBILITY_SETTINGS"
AccessibilityService is special and cannot be started programmatically.
In instrumented tests I start my accessibility service like this:
private fun enableAccessibilityService() {
val packageName = "com.example"
val className = "$packageName.service.MyService"
val string = "enabled_accessibility_services"
val cmd = "settings put secure $string $packageName/$className"
InstrumentationRegistry.getInstrumentation()
.getUiAutomation(UiAutomation.FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES)
.executeShellCommand(cmd)
.close()
TimeUnit.SECONDS.sleep(3)
}
I tested on Android 6 and 8. This also works for non-system apps.
Here is the working solution (if your activity is not running it will disable itself)
@Override
protected void onServiceConnected() {
super.onServiceConnected();
Toast.makeText(this, "Connected!",Toast.LENGTH_SHORT).show();
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
serviceChecker();
}
}, 0, 5, TimeUnit.SECONDS);
}
private void serviceChecker(){
if(!isActivityRunning(MainActivity.class)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
disableSelf();
}
}
}
protected Boolean isActivityRunning(Class activityClass)
{
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
return true;
}
return false;
}
I found this post: How to programmatically check if a service is declared in AndroidManifest.xml?. The top answer talks about PackageManager, which tells you what is running.
From Android 6.0 you can use:
adb shell settings put secure enabled_accessibility_services packagname/servicename
The settings.db from old releases is no longer present on Android 6.0.