Android: How to safely unbind a service

后端 未结 8 935
深忆病人
深忆病人 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: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 service;
        private boolean attemptingToBind = false;
        private boolean bound = false;
    
        public ServiceConnectionManager(Context context, Class 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;
            }
        }
    
    }
    

提交回复
热议问题