My app extends Android's AccessibilityService to monitor the currently active app. In order to detect changes in activities I have to register my service and get the user to consent to allow the permission. As a convenience to the user I detect whether my service is currently enabled when my app starts, if not enabled e.g. when the app is installed then I redirect the user to the Settings Accessibility page to allow them to enable the service. The following code checks whether my service is currently enabled, the id parameter is the id of my service e.g. com.foo.bar/.MyService syntax:
private boolean isAccessibilityEnabled(String id) {
AccessibilityManager am = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityEvent.TYPES_ALL_MASK);
for (AccessibilityServiceInfo service : enabledServices) {
if (id.equals(service.getId())) {
return true;
}
}
return false;
}
I've seen two scenarios where this check fails even though I know the service is enabled. Firstly if I debug my app from Android Studio this fails and enabledServices
is empty, if I run (rather than debug) it works perfectly and returns a single entry in enabledServices
. The second scenario I've noticed where it fails is when I run the adb backup
command to backup my app, if my app is currently visible when the backup prompt comes up then when the backup completes my app's main activity onCreate
is executed and the isAccessibilityEnabled
method is checked and again fails to see my service is already enabled.
Is there a special case I need to take into account when calling getEnabledAccessibilityServiceList
or is there a reason why my service isn't returned even though when I look in the Accessibility Settings page I can see the service is enabled.
There is an alternative way to query if an accessibility service is enabled, I've used the approach described here - Detect if my accessibility service is enabled and it seems to get around the issues I was encountering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With