Android: How to safely unbind a service
Here you can find a nice explanation and source codes how to work with bound services. In your case you should override methods (onServiceConnected
and onServiceDisconnected
) of ServiceConnection
object. Then you can just check mBound
variable in your code.
Try this:
boolean isBound = false;
...
isBound = getApplicationContext().bindService( new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE );
...
if (isBound)
getApplicationContext().unbindService(serviceConnection);
Note:
You should use same context
for binding a service and unbinding a service. If you are binding Service with getApplicationContext()
so you should also use getApplicationContext.unbindService(..)