I have a service which is binded to application context like this:
getApplicationContext().bindService( new Intent(this, ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE ); protected void onDestroy() { super.onDestroy(); getApplicationContext().unbindService(serviceConnection); }
For some reason, only sometimes the application context does not bind properly (I can't fix that part), however in onDestroy() I do unbindservice
which throws an error
java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection.
My question is: Is there a way to call unbindservice
safely or check if it is already bound to a service before unbinding it?
Thanks in advance.
A bound service is the server in a client-server interface. It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC).
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
Use both startService() and bindService() , if needed. How can I get an instance to the service started if I do not use bindService? Either use bindService() with startService() , or use a singleton. By "using a singleton" you mean that I should declare my methods static in the service class?
To start the service, call startService(intent) and to stop the service, call stopService(intent) .
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(..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With