Question

I am building an AccessabilityService targeting API level 8 but i want to use features introduced in API level 18 (getViewIdResourceName()). This should be possible by using the Android Support Library v4 as this feature is available there. I already got the library up and running but i am not sure how to change my code to use it.

Here is what i do:

import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import android.support.v4.accessibilityservice.*;
import android.support.v4.view.accessibility.*;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.ViewCompat;

public class MyAccessabilityService extends AccessibilityService {

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.i(TAG, event.getSource().getViewIdResourceName());
    }
}

When i set android:minSdkVersion to 18 in the manifest.xml everything works just fine. But when i change it to 8, Eclipse gives me a warning that the android.support.v4.* imports are not being used, and an error Call requires API level 14 (current min is 8): android.view.accessibility.AccessibilityEvent#getSource.

Was it helpful?

Solution

You can't directly call event.getSource() because that method doesn't exist on API 8. Instead, you need to use the AccessibilityRecordCompat and AccessibilityNodeInfoCompat classes.

AccessibilityRecordCompat record = AccessibilityEventCompat.asRecord(event);
AccessibilityNodeInfoCompat node = record.getSource();
Log.i(TAG, node.getViewIdResourceName());

These classes wrap the actual event and node objects, and they provide stub implementations when methods are not available on the current device API. So if you run the snippet above on API 8, it will crash with a NullPointerException because getSource() is an API 14+ method and will always return null on earlier APIs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top