Android: How to safely unbind a service

后端 未结 8 951
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2020-12-12 16:47

    I think that guide is not completely correct as mentioned here Surya Wijaya Madjid. Memory leaks can occur when bound service is destryed and not re-connected yet.

    I think that this approach is needed:

    Service mService;
    
    private final ServiceConnection mServiceConnection = new ServiceConnection()
    {
        boolean bound = false;
    
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            mService = null;
        }
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            mService = ((MyService.ServiceBinder) service).getService();
    
            if (!bound)
            {
                // do some action - service is bound for the first time
                bound = true;
            }
        }
    };
    
    @Override
    public void onDestroy()
    {
        if (mService != null)
        {
            // do some finalization with mService
        }
    
        if (mServiceConnection.bound)
        {
            mServiceConnection.bound = false;
            unbindService(mServiceConnection);
        }
        super.onDestroy();
    }
    
    public void someMethod()
    {
        if (mService != null)
        {
            // to test whether Service is available, I have to test mService, not     mServiceConnection.bound
        }
    }
    

提交回复
热议问题