IAE: Service not registered on unbindService after Service.stopSelf

1.4k views Asked by At

I'm binding to an android Service as demonstrated in the JavaDoc

private boolean bound = false;
private MyService service = null;

private final ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i(TAG, "Service connected");
        service = (MyService) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(TAG, "Service disconnected");
        service = null;
    }
};

@Override
public void onResume() {
    super.onResume();

    Intent intent = new Intent(this, MyService.class);
    if (bindService(intent, connection, Context.BIND_ABOVE_CLIENT)) {
        bound = true;
    } else {
        Log.w(TAG, "Service bind failed");
    }
}

@Override
public void onPause() {
    if (bound) {
        unbindService(connection);
        bound = false;
    }
    super.onPause();
}

Sometimes, the Service stops itself calling stopSelf or is stopped by stopService, resulting in all clients being unbound. But the variable bound here is still true, so onPause will throw the following Exception:

 java.lang.IllegalArgumentException: Service not registered: de.ncoder.sensorsystem.android.app.MainActivity$1@359da29
            at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1022)
            at android.app.ContextImpl.unbindService(ContextImpl.java:1802)
            at android.content.ContextWrapper.unbindService(ContextWrapper.java:550)
            at de.ncoder.sensorsystem.android.app.MainActivity.onPause(MainActivity.java:121)
            at android.app.Activity.performPause(Activity.java:6044)
            ...

Is there a simple way to check if a Service is still bound and alive? As far as I know, onServiceDisconnected will leave bindings active (as it is only called under extreme circumstances, where the Service is hopefully being restarted soon), so setting bound to false there won't help.

2

There are 2 answers

2
kalyan pvs On

When you call stopSelf() in your service then your onSerivceDisconnected() will get called

So change bound value to false in onSerivceDisconnected() of your Activity

 @Override
public void onServiceDisconnected(ComponentName name) {
    Log.i(TAG, "Service disconnected");
    bound=false;
    service = null;
}
0
esentsov On

In the most situations you would like to have service running while an activity is bind to it. The solutions for this case - add flag BIND_AUTO_CREATE to service binding call and service will run until you call unbind even if stopService or stopSelf were called.

Otherwise, as far as I know, the only option is to catch the exception.