Ble Connection
Manages a Bluetooth Low Energy (BLE) connection to a remote device.
This class provides a high-level API for establishing and managing BLE connections, including reading and writing characteristics, enabling/disabling notifications, and handling device bonding. It wraps a ConnectionStateMachine to manage the underlying connection state and provides coroutine-based suspend functions for asynchronous BLE operations.
Usage Example
val connection = BleConnection(context, bluetoothDevice)
connection.connect()
// Observe connection state
connection.connectionStateFlow.collect { state ->
when (state) {
ConnectionState.Connected -> println("Connected!")
ConnectionState.Disconnected -> println("Disconnected")
// Handle other states...
}
}
// Read a characteristic
val value = connection.readCharacteristic(serviceUuid, characteristicUuid)
// Don't forget to close when done
connection.close()Parameters
The Android Context used for BLE operations. An application context is recommended to avoid memory leaks.
The BluetoothDevice to connect to.
Optional BondManager for handling device bonding operations. If null, bond will return an empty flow.
Whether to automatically attempt reconnection when the connection is lost unexpectedly. Defaults to true.
Base delay in milliseconds for exponential backoff reconnection. The actual delay increases exponentially with each attempt. Defaults to ConnectionStateMachine.DEFAULT_RECONNECT_DELAY_MS.
Maximum delay in milliseconds between reconnection attempts. The exponential backoff will be capped at this value. Defaults to ConnectionStateMachine.DEFAULT_MAX_RECONNECT_DELAY_MS.
Maximum number of reconnection attempts before giving up. When this limit is reached, the state transitions to ConnectionState.Error. Defaults to ConnectionStateMachine.DEFAULT_MAX_RECONNECT_ATTEMPTS.
See also
Constructors
Properties
Functions
Binds this BleConnection to a LifecycleOwner for automatic lifecycle management.
Clears the service cache for this device.
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.
Gets the list of discovered GATT services for this device.
Reads the value of a characteristic from the connected BLE device.
Resets the reconnect attempt counter to zero.
Writes a value to a characteristic on the connected BLE device.
Writes a large value to a characteristic using sequential chunked writes.