I have a service which is binded to application context like this:
getApplicationContext().bindService(
new Intent(this, ServiceUI.class
Why do we get this error?
When you try to unregister a service which is not registered.
What are some common examples?
unBind(mserviceConnection) more than bind(...) First point is self explanatory. Lets explore the second source of error more deeply. Debug your bind() and unbind() calls. If you see calls in these order then your application will end up getting the IllegalArgumentException.
How can we avoid this?
There are two ways you should consider to bind and unbind a service in Activity. Android docs recommend that
bindService() in
onStart()and unbindService() inonStop()
Your Activity {
@Override
public void onStart(){
super.onStart();
bindService(intent, mConnection , Context.BIND_AUTO_CREATE);
}
@Override
public void onStop(){
super.onStop();
unbindService(mConnection);
}
}
bindService() in
onCreate()and unbindService() inonDestroy()
Your Activity {
@Override
public void onCreate(Bindle sis){
super.onCreate(sis);
....
bindService(intent, mConnection , Context.BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
}