Android: How to safely unbind a service

后端 未结 8 931
深忆病人
深忆病人 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:06

    Not sure about all the above answers, it seemed far too complicated while none of these would fit the issue I had.

    Only binding/unbinding once at a time, and the service was definitely bound at the time of the unbind() call. Don't want to leak anything, so I just made sure I was using the same context for the bind() and unbind() calls and that solved it permanently! Doing something like this:

    any_context.getApplicationContext().bind(...);
    
    ...
    
    another_context.getApplicationContext().unbind(...);
    
    0 讨论(0)
  • 2020-12-12 17:08

    I found there are two issues. Attempting to bind more than once and also attempting to unbind more than once.

    Solution:

    public class ServiceConnectionManager implements ServiceConnection {
    
        private final Context context;
        private final Class<? extends Service> service;
        private boolean attemptingToBind = false;
        private boolean bound = false;
    
        public ServiceConnectionManager(Context context, Class<? extends Service> service) {
            this.context = context;
            this.service = service;
        }
    
        public void bindToService() {
            if (!attemptingToBind) {
                attemptingToBind = true;
                context.bindService(new Intent(context, service), this, Context.BIND_AUTO_CREATE);
            }
        }
    
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            attemptingToBind = false;
            bound = true;
        }
    
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            bound = false;
        }
    
        public void unbindFromService() {
            attemptingToBind = false;
            if (bound) {
                context.unbindService(this);
                bound = false;
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题