开发者

IllegalArgumentException: Service not registered:

开发者 https://www.devze.com 2023-01-03 18:32 出处:网络
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 acti

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

IllegalArgumentException: Service not registered:

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() in onStop()

Case 2: When you want to interact with service even the Activity is in Background then

bindService() in onCreate() and unbindService() in onDestroy()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消