'AccessibilityService static instance sometimes is null and I can't understand why or how to fix it

This is my AccesibilityService class:

public class MyAS extends AccessibilityService {

    public static MyAS myAS;


    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        myAS = this;
    }


    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
       
    }


    @Override
    public void onInterrupt() {

    }


    @Override
    public boolean onUnbind(Intent intent) {
        disableSelf();
        return super.onUnbind(intent);
    }



    public static MyAS getMyAS(){
        return myAS;
    }


}

And this is my Service class:

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        
        MyAS.getMyAS().dispatchGesture(...);
        
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


}

As you can see I basically assign the AccesibilityService instance to a static instance. And then I use that static instance in MyService in order to dispatch a gesture.

On android 9 works fine, at least so far. On android 11 sometimes works fine but other times sadly I get a NullPointerException because basically MyAS.getMyAS() return null. But the AccessibilityService is enabled, as a matter of fact I don't let the user start MyService unless the toggle of the AccessibilityService is on.

What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source