androidkotlinserviceandroid-lifecyclebounds

Is it possible to bind and unbind a bound service via button click in Android?


Can I safely perform bindService() and unbindService() when a button is clicked inside an Activity or Fragment, instead of binding in onStart() and unbinding in onStop()?

Will it cause any issue if the Activity is closed while the service is still bound this way?

btnBind.setOnClickListener {
    bindService(intent, connection, Context.BIND_AUTO_CREATE)
}

btnUnbind.setOnClickListener {
    unbindService(connection)
}

Is this approach okay, or should I always manage the binding inside lifecycle callbacks for safety?


Solution

  • Key issues to watch out for :

    Calling unbindService() without being bound If you call unbindService() when the service is not currently bound, Android will throw an IllegalArgumentException:

    java.lang.IllegalArgumentException: Service not registered

    Always track binding state using a flag:

    var isBound = false
    
    btnBind.setOnClickListener {
        if (!isBound) {
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
            isBound = true
        }
    }
    
    btnUnbind.setOnClickListener {
        if (isBound) {
            unbindService(connection)
            isBound = false
        }
    }
    

    Activity destruction without unbinding If the user closes the Activity (via back press or system), and it was still bound to the service, Android will automatically unbind it only if the service was bound using Context.bindService() and the context is the Activity itself. But you should not rely on this. If you forget to unbind, it may cause memory leaks or other side effects.

    Lifecycle mismatch Manual binding doesn't automatically follow the Activity lifecycle (like onStart()/onStop()), which can lead to inconsistency if the Activity is recreated (e.g., due to a config change).