android bind to AccessibilityService

2019-05-18 12:06发布

问题:

I have created an android service, which is an AccessibilityService. From my activity, I would like to bind to that service. There is no inter process communication, so I have tried creating a local Binder implementation that just returns the service (as in this example http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html).

The problem is that onBind in AccessibilityService is final and I cannot override it to return my local binder.

Does this mean I need to use AIDL if I want to bind to the service?

回答1:

No, it means that you cannot bind to the service, period. You would need to override onBind() for AIDL.



回答2:

You can't bind to AccessibilityService because it's onBind() method declared final. BUT, you can use it's instance by storing it in a static field.

In your MyAccessbilityService class:

1.Create static field of the type of your AccessibilityService

private static MyAccessibilityService myAccessibilityServiceInstance;

2.Initialize it in method onServiceConnected()

@Override
protected void onServiceConnected() {
    super.onServiceConnected();
    myAccessibilityServiceInstance = this;
}

3.Clear it when AccessibilityService is turned off in onUnbind() method:

@Override
public boolean onUnbind(Intent intent) {
    myAccessibilityServiceInstance = null;
    return super.onUnbind(intent);
}

4.Create a getter for your instance and let's add annotation @Nullable since we don't know in which period of service's life cycle it will be called

@Nullable
public static MyAccessibilityService getInstance(){
    return myAccessibilityServiceInstance;
}

and finally in your Activity or wherever you need it:

    MyAccessibilityService accessibilityService = MyAccessibilityService .getInstance();
    if(accessibilityService != null){
        //do smth here:
    }

Implemented in my app, works fine so far. Thanks to alanv in his reply https://stackoverflow.com/a/12557673/5502121