How to use Accessibility Service in Android

Accessibility Service is used to assist users with disabilities. Accessibility services are background services which is invoked by the system on receiving specific input in the form of AccessibilityEventInfo. This service can be implemented to to receive state changes in the user interface like button click, text change in EditText. In this example I am going to show here how to access texts in EditText and how to register Accessibility service to listen to changes in EditText field.

AccessibilityService is declared in the AndroidManifest.xml and its method onAccessibilityEvent is implemented to receive system callbacks. Let’s create our accessibility service to receive EditText callbacks.

Create a new Android project and create a service named TextAccessibilityService.java

In this service class we extend the class with AccessibilityService and implement onAccessibilityEvent method to receive callbacks. Here we are listening to system callback for any changes tracked in EditText fields.

Declare AccessibilityService in AndroidManifest.xml. We can configure the service to receive specific types of events. This is configured by adding meta-data with key android.accessibilityservice and values defined in a resource file.

Create configuration data file accessibility_config.xml for the service.

Define accessibility_service_description in strings.xml

All the events that can be tracked are listed in google reference.

Enable AccessibilityService

Accessibility Service example in android.

Now it’s time to get user consent and let user enable the accessibility service from the system settings. We can facilitate the user by directly opening the accessibility settings window from our application activity.

build.gradle

Check if our registered accessibility service is enabled in the system or not. This can be checked programatically. Create a new function in your activity isAccessibilityServiceEnabled which will check if our service is enabled or not.

MainActivity.java

Call the above function to check the status. If our service is not enabled then navigate the user to Accessibility Settings.

Create layout for activity. activity_main.xml

After enabling the service you will get system callbacks for any changes in any application done by the user in EditText. Similarly other events can be registered and you can get the list of all the attributes here.

Leave a Reply