A Kotlin Multiplatform library for Bluetooth functionality in Jetpack Compose applications.
- Cross-platform support: Works on Android and iOS.
- Easy-to-use API: Simplified Bluetooth connectivity for Compose apps.
- Device scanning: Discover and connect to nearby Bluetooth devices.
- State management: Monitor connection status and device states.
- Bluetooth State Management: Monitor Bluetooth State allowing app to respond accordingly.
- Paired and Connected Devices Management: Retrieve and manage paired and connected devices.
- Permission Handling: Request and check Bluetooth permissions.
Add the dependency to your build.gradle.kts:
commonMain.dependencies {
implementation("network.chaintech:cmp-bluetooth-manager:1.0.0")
}Ensure you add the following permissions in your AndroidManifest.xml:
<!-- Bluetooth Permissions (For Android 11 and below) -->
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<!-- Bluetooth Permissions (For Android 12 and above) -->
<uses-permission
android:name="android.permission.BLUETOOTH_CONNECT"
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<!-- Location Permissions (For Bluetooth Scanning for Android 11 or below) -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Bluetooth Hardware Requirement -->
<uses-feature android:name="android.hardware.bluetooth" />For iOS, add the following keys to your Info.plist file:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>We require Bluetooth access to connect to nearby devices.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We use Bluetooth to communicate with other devices.</string>val bluetoothManager = BluetoothManager()@Composable
fun RequestPermissions() {
RequestBluetoothPermission { isGranted ->
if (isGranted) {
println("Bluetooth permission granted")
} else {
println("Bluetooth permission denied")
}
}
}
val isPermissionGranted = isBluetoothPermissionGranted()
if (isPermissionGranted) {
println("Bluetooth permission is already granted")
} else {
println("Bluetooth permission is required")
}The bluetoothState flow updates whenever the Bluetooth state changes, allowing the app to respond accordingly.
LaunchedEffect(Unit) {
bluetoothManager.bluetoothState.collectLatest {(state, device)->
when(state){
BluetoothState.IDLE -> println("Bluetooth Idle")
BluetoothState.BLUETOOTH_ENABLED -> println("Bluetooth Enabled ")
BluetoothState.BLUETOOTH_DISABLED -> println("Bluetooth Disabled ")
BluetoothState.DEVICE_CONNECTED -> println("Device Connected ${device?.name}")
BluetoothState.DEVICE_DISCONNECTED -> println("Device Disconnected ${device?.name}")
}
}
}Start scanning for nearby Bluetooth devices and receive updates on discovered devices and scan state changes.
bluetoothManager.startScan(
onDeviceFound = { device -> },
onScanStateChanged = { state ->
when (state) {
BluetoothScanState.IDLE -> {}
BluetoothScanState.SCANNING -> {}
BluetoothScanState.STOPPED -> {}
}
},
onError = { error -> println("Error: ${error}") }
)Establish a connection with a Bluetooth device and monitor the connection state. A Bluetooth device (BluetoothPeripheral) is required to establish a connection. You can get this device by scanning, retrieving paired devices, or checking currently connected devices. Service UUID is optional and can be used to connect to a specific type of service on the device.
bluetoothManager.connectToDevice(
device = BluetoothPeripheral(), // Bluetooth Device
uuid = YOUR_SERVICE_UUID, // Optional
onConnectionStateChanged = { state ->
when (state) {
BluetoothConnectionState.DISCONNECTED -> println("Device Disconnected")
BluetoothConnectionState.CONNECTING -> println("Connecting...")
BluetoothConnectionState.CONNECTED -> println("Device Connected")
BluetoothConnectionState.ERROR -> println("Connection Error")
}
},
onError = { error -> println("Connection error: ${error}") }
)Terminate an active Bluetooth connection with a device.
bluetoothManager.disconnectDevice(
device = BluetoothPeripheral() // Bluetooth Device ,
onSuccess = { println("Device disconnected successfully") },
onError = { error -> println("Error disconnecting: ${error}") }
)Remove a Bluetooth device from the paired devices list.
bluetoothManager.unpairBluetoothDevice(
device = BluetoothPeripheral() // Bluetooth Device,
onSuccess = { println("Device unpaired successfully") },
onError = { error -> println("Error unpairing device: ${error}") }
)Retrieve a list of devices that have been paired with the system.
val pairedDevices = bluetoothManager.getPairedDevices()
pairedDevices.forEach { device -> println("Paired device: ${device.name}") }Fetch the list of currently connected Bluetooth devices.
bluetoothManager.getConnectedDevices { device ->
println("Connected device: ${device.name}")
}Initialize a Bluetooth to allow other devices to connect. To ensure that only devices with the same UUID can connect, pass a unique Service UUID while making the device visible and while connecting. If the UUIDs do not match, the connection will fail.
bluetoothManager.makeDeviceVisible(
uuid = YOUR_SERVICE_UUID, //Unique UUID Required
onConnectionStateChanged = { state ->
when (state) {
BluetoothServerConnectionState.LISTENING -> println("Listening")
BluetoothServerConnectionState.DISCONNECTED -> println("Disconnected")
BluetoothServerConnectionState.CONNECTED -> println("Connected")
BluetoothServerConnectionState.ERROR -> println("Error")
}
},
onError = { error -> println("Server error: ${error}") }
)Fetch the name of the current Bluetooth device.
val deviceName = bluetoothManager.getDeviceName()The demo project utilizes the following libraries:
SDP & SSP for Compose Multiplatform β Scalable size units for responsive UI
- sdp-ssp-compose-multiplatform β network.chaintech:sdp-ssp-compose-multiplatform
Connectivity Monitor β Seamless Network Monitoring for Compose Multiplatform
- CMPToast β network.chaintech:cmptoast
For an in-depth guide and detailed explanation, check out our comprehensive Medium Blog Post.
Stay connected and keep up with our latest innovations! πΌ Let's innovate together!