Android: How to safely unbind a service

后端 未结 8 933
深忆病人
深忆病人 2020-12-12 16:44

I have a service which is binded to application context like this:

getApplicationContext().bindService(
                    new Intent(this, ServiceUI.class         


        
8条回答
  •  不思量自难忘°
    2020-12-12 17:04

    Why do we get this error?

    When you try to unregister a service which is not registered.

    What are some common examples?

    • Binding and Unbinding a service with different Context.
    • calling 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

    • If you want to interact with a service only when the Activity is visible then

    bindService() in onStart() and unbindService() in onStop()

    Your Activity {
    
        @Override
        public void onStart(){
           super.onStart();
           bindService(intent, mConnection , Context.BIND_AUTO_CREATE);
        }
    
        @Override
        public void onStop(){
           super.onStop();
           unbindService(mConnection);
        }
    
    } 
    
    • If you want to interact with a service even an Activity is in Background then

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

    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);
        }         
    
    }
    

提交回复
热议问题