Skip to content

About

No description, website, or topics provided.

Resources

Stars

20 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

badge-android badge-ios

Compose Multiplatform Bluetooth Manager

A Kotlin Multiplatform library for Bluetooth functionality in Jetpack Compose applications.

plot

✨ Features

  • 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.

📦 Installation

Add the dependency to your build.gradle.kts:

commonMain.dependencies {
    implementation("network.chaintech:cmp-bluetooth-manager:1.0.0")
}

🔐 Permissions

Android

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" />

iOS

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>

📖 Usage

Initializing Bluetooth

val bluetoothManager = BluetoothManager()

Checking and Requesting Bluetooth Permissions

@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")
}

Bluetooth State

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}")
            }
    }
}

Scanning for Devices

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}") }
)

Connecting to a Device

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}") }
)

Disconnecting a Device

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}") }
)

Unpairing a Device

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}") }
)

Getting Paired Devices

Retrieve a list of devices that have been paired with the system.

val pairedDevices = bluetoothManager.getPairedDevices()
pairedDevices.forEach { device -> println("Paired device: ${device.name}") }

Getting Connected Devices

Fetch the list of currently connected Bluetooth devices.

bluetoothManager.getConnectedDevices { device ->
    println("Connected device: ${device.name}")
}

Make Device Available for others

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}") }
)

Retrieving Device Name

Fetch the name of the current Bluetooth device.

val deviceName = bluetoothManager.getDeviceName()

🛠️ Libraries Used in Demo

The demo project utilizes the following libraries:

SDP & SSP for Compose Multiplatform – Scalable size units for responsive UI

Connectivity Monitor – Seamless Network Monitoring for Compose Multiplatform

  • CMPToast – network.chaintech:cmptoast

📖 Detailed Explanation

For an in-depth guide and detailed explanation, check out our comprehensive Medium Blog Post.

Medium

Stay connected and keep up with our latest innovations! 💼 Let's innovate together!

LinkedIn


About

No description, website, or topics provided.

Resources

Stars

20 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages