Duc Minh.T
Duc Minh.T

Reputation: 5

How to use Accessibility Service with TYPE_WINDOW_STATE_CHANGED

I try to use Accessibility Service to handle event when a new activity or window is opened. But it doesn't work.

**First, I implement a accessibility service class look like:

public class DemoAccessibilityService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    System.out.println(" DemoAccessibilityService change= " + event.getAction());

}

@Override
public void onInterrupt() {
}

@Override
protected void onServiceConnected() {
    System.out.println("DemoAccessibilityService connected");
    super.onServiceConnected();
    AccessibilityServiceInfo config = new AccessibilityServiceInfo();
    config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
    config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;

    if (Build.VERSION.SDK_INT >= 16)
        config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;

    setServiceInfo(config);
}

@Override
public void onDestroy() {
    System.out.println("DemoAccessibilityService destroy");
    super.onDestroy();
}

}

There are 2 options to config service: (1) use .xml file or (2) config dinamically on source code. I had demo_accessibility.xml config file:

<accessibility-service
 xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools"
 android:accessibilityEventTypes="typeWindowStateChanged"
 android:accessibilityFeedbackType="feedbackGeneric"
 android:accessibilityFlags="flagIncludeNotImportantViews"
 tools:ignore="UnusedAttribute"
 android:packageNames="com.android.systemui"

/>

** Then, I declared it in AndroidManifest.xml like this:

<service android:name="demo.android.accessibility.DemoAccessibilityService"
             android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data android:name="android.accessibilityservice"
                   android:resource="@xml/demo_accessibility"/>
    </service>

After build in devices, I go onto Settings and turn on in Accessibility category. But it doesn't work! What should I do?

Upvotes: 0

Views: 2674

Answers (2)

behelit
behelit

Reputation: 1794

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
        runningPackageName = event.getPackageName().toString();
        Log.d("RunningAppsService", "Current app changed: " + runningPackageName);
    }
}

Upvotes: 0

Kunal
Kunal

Reputation: 55

you have to add android:canRetrieveWindowContent="true" inside demo_accessibility.xml file

Upvotes: 0

Related Questions