Search code examples
androidservicebluetoothandroid-serviceandroid-service-binding

Android unbind Service on App crash or exit


I am working on a Android app that binds to a Android service.

The problem is that that Android service is responsible of a Bluetooth connection with another device.

For now, my service exposes a DisconnectBluetooth() method, that will end the Bluetooth connection.

What I do is to call that DisconnectBluetooth method followed by a call to unbindService, within my onDestroy method, so when the app stops, the Bluetooth connection will be closed, and the service will be unbound.

The thing is that if my app crashes, or sometimes when I force it to exit by swipping it in the App Selector, the onDestroy method won't be called. The app will then be quitted, but the service is still alive, and so the Bluetooth connection is still alive too.

What can I do, to be sure to close the Bluetooth connection, and if possible unbind the service ?

@Override
protected void onDestroy() {
      if (_api.isConnect()) { //<-- If bound to service, and everything OK
        _api.DisonnectBluetooth(); //<-- Close BT connection with device
        _api.ReleaseService(); //<-- Unbinds service
      }
    }
    super.onDestroy();
}

Solution

  • I always thought overriding onUnbind() method, would be called only if activity explicitly calls unbindService() method.

    But no, even if my app crashes or force exit by swipping recent app selector, it is called. I so decided to use onunbind rather than onTaskRemoved

    NOTE : I am using Xamarin, and I can't guarantee this to work on Java Android