Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to safely unbind a service

Tags:

android

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.

like image 471
2ndlife Avatar asked Dec 23 '11 09:12

2ndlife


People also ask

What is a bound service in Android?

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).

How do you stop a service in Android?

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.

How do I find my service instance android?

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?

How do I stop a service in Android Studio?

To start the service, call startService(intent) and to stop the service, call stopService(intent) .


1 Answers

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(..)

like image 188
Andrey Novikov Avatar answered Oct 02 '22 17:10

Andrey Novikov