I have multiple activities in my app, every activity calls bindservice
and unbindservice
to fetch data. In the first activity bindservice
and unbindservice
work fi开发者_开发技巧ne. In the second activity (which reuses the same service) bind service method works fine, but unbindservice
method gives exception:
IllegalArgumentException: Service not registered:
Please help.
NikkyD's question is very good and it helped find the cause of this exception in my case. To anyone out there experiencing the same problem, make sure that your bindService call and unbindService call are done against the same context. Hope it helps.
Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again. http://developer.android.com/guide/components/bound-services.html Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed. So,please check if you have kill the service at first time. May be pass the IBind to every activity much more better.Because it just return only one.
Why do we get this error?
Sometimes we get this error when in an Activity unbindService()
gets called before bindService()
A common example
is when we bindService in onCreate()
and unbindService in onPause()
or onStop()
of Activity.
How to avoid?
Case 1: When you want to interact with the service only when the Activity is visible then follow this order.
bindService() in
onStart()
and unbindService() inonStop()
Case 2: When you want to interact with service even the Activity is in Background then
bindService() in
onCreate()
and unbindService() inonDestroy()
I had this problem with an old API. (Android 2.2) I got this error when I called this method: (from the billing tutorial)
@Override
public void onDestroy() {
super.onDestroy();
try {
if (mHelper != null) mHelper.dispose();
mHelper = null;
}catch (IllegalArgumentException e){
Log.d("TMA Billing Android 2.2","Error: "+e.getMessage());
mHelper = null;
}
}
As you can see, I surrounded it with Try Catch and now it is working with no problem on Android 2.2.
精彩评论