Skip to content

Instantly share code, notes, and snippets.

@MFlisar
Created December 10, 2015 07:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MFlisar/f7f32c386d77751648f9 to your computer and use it in GitHub Desktop.
Save MFlisar/f7f32c386d77751648f9 to your computer and use it in GitHub Desktop.
public class WindowChangeDetectingService extends AccessibilityService {
@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;// | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;// | AccessibilityServiceInfo.FEEDBACK_SPOKEN;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event)
{
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
{
String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
String activityName = event.getClassName() != null ? event.getClassName().toString() : "";
// do something with the information
// ...
}
else if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
{
L.d(this, "event: " + event.toString());
}
}
@Override
public void onInterrupt() {}
}
@MFlisar
Copy link
Author

MFlisar commented Dec 10, 2015

don't forget to add the service to the manifest:

<service
        android:label="@string/app_name"
        android:name=".services.WindowChangeDetectingService"
        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/accessibilityservice"/>
    </service>

The xml looks something like following:

<?xml version="1.0" encoding="utf-8"?>
<!-- These options MUST be specified here in order for the events to be received on first start in Android 4.1.1 -->
<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
android:description="@string/accessibility_service_description"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment