Lifecycle Aware Ble Connection
A lifecycle-aware wrapper for BleConnection that automatically manages the BLE connection lifecycle in response to Android lifecycle events.
This class implements DefaultLifecycleObserver to observe the lifecycle of an Android component (such as an Activity or Fragment) and automatically disconnect from the BLE device when the lifecycle owner is stopped, and close the connection when the lifecycle owner is destroyed.
This helps prevent resource leaks and ensures that BLE connections are properly cleaned up when the associated UI component is no longer active.
Lifecycle Behavior
onStop: Automatically calls disconnect to gracefully disconnect from the BLE device while keeping resources allocated for potential reconnection.
onDestroy: Automatically calls close to fully release all resources and removes this observer from the lifecycle.
Usage Example
class MyActivity : AppCompatActivity() {
private lateinit var connection: LifecycleAwareBleConnection
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bleConnection = BleConnection(applicationContext, bluetoothDevice)
connection = bleConnection.bindToLifecycle(this)
// Use the connection - it will automatically be managed
connection.connect()
// Observe connection state
lifecycleScope.launch {
connection.connectionStateFlow.collect { state ->
// Handle state changes
}
}
}
// No need to manually disconnect or close - handled automatically
}Alternative Usage with Extension Function
val connection = BleConnection(context, device).bindToLifecycle(lifecycleOwner)
connection.connect()Parameters
The underlying BleConnection instance to wrap.
The LifecycleOwner whose lifecycle will control this connection. Typically an Activity, Fragment, or other lifecycle-aware component.
See also
Properties
Functions
Disables notifications for a characteristic.
Disconnects from the BLE device while keeping resources allocated.
Enables notifications for a characteristic and registers a callback for received values.
Called when the LifecycleOwner is destroyed.
Called when the LifecycleOwner is stopped.
Reads the value of a characteristic from the connected BLE device.
Returns the underlying BleConnection instance.
Writes a value to a characteristic on the connected BLE device.