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.
When you call
stopSelf()
in your service then youronSerivceDisconnected()
will get calledSo change
bound
value tofalse
inonSerivceDisconnected()
of yourActivity