Search code examples
accessibilityserviceaccessibilityaccessibility-api

Android Accessibility Service stopped working after a day or two on Oreo


Background:

I have a class which extends from AccessibilityService. Whenever a window is changed following function is called which gives me the application name of the foreground application.

@Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

}

Following is the configuration I set:

 @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        //Configure these here for compatibility with API 13 and below.
        AccessibilityServiceInfo config = new AccessibilityServiceInfo();
        config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
        config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;

        if (Build.VERSION.SDK_INT >= 16) {   //Just in case this helps
            config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
        }
        setServiceInfo(config);
    }

AccessibilityService.xml

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_explanation"
android:accessibilityEventTypes="typeWindowStateChanged|typeAllMask"
android:accessibilityFeedbackType="feedbackSpoken|feedbackHaptic|feedbackAudible|feedbackVisual|feedbackGeneric|feedbackAllMask"
android:notificationTimeout="100" android:canRetrieveWindowContent="true" />

The Problem: It works fine for some time, but after a day or two it suddenly stops working. It doesn't call the onAccessibilityEvent(AccessibilityEvent event) function. Although the accessibility service of this application is enabled but still it doesn't show the application name when window is changed.

May be it doesn't work if the application comes back from sleep mode? I had to reinstall the application on top of my debug build and then again it started working but for how long.

Question: How can I make sure it always return me the application name when window is changed?


Solution

  • Just restart your app. This is because Accessibility Service is managed by the Android OS, so if any thing causes your service to crash, it will be killed and rescheduled to be started at some time in the fture that you can not control. So it is possible that your service has been killed.