Pairing and connection
To set up the bracelet and the Android SDK here are the main steps to implement:
- Pair and connect to the bracelet (this page)
- Set up the bracelet parameters
- Set up the automatic data transfer from the bracelet to the Android SDK database
- Retrieve the data
Recommended setup shows the four steps together in one app.
Several examples in this guide use DeviceManager. DeviceManager is not part of the SDK. It is a small helper in the sample app (com.corsano.sdk.sample.device.DeviceManager) that keeps hold of the currently selected BleDevice. Wherever you see DeviceManager.getCurrentDevice(), use the way your own app keeps the connected bracelet. The SDK call is BleSdk.getInstance().getDevice(address).
Step 1: Pairing to the bracelet
Do this once per bracelet:
- Check that Bluetooth is on and ask for the scan permissions.
- Scan for the bracelets nearby and let the user choose one.
- Scan again for that bracelet until the user presses its pusher (a security step).
- Ask for the connect permission and call
connect(keepAlive = true). Android creates the bond (the pairing) during the first connection. - Store the bracelet's address. At the next start of the app, call
getDevice(address)andconnect(keepAlive = true)again. The two scans are not needed again.
Before any of this, CorsanoSdk.initialize must have run, see Getting Started.
After the connection, the bracelet must be initialized before it accepts commands. See Bracelet Initialization.
What you get and where it arrives
| You want | Call | Where the value arrives |
|---|---|---|
| Whether Bluetooth is on | BleSdk.getInstance().getBluetooth().getState() | Return value (BluetoothState); changes in Bluetooth.StateListener.onBluetoothStateChanged |
| The bracelets nearby | BleScanner.startScan | BleScanEvent.BleScanResults.results in the scan listener |
| The pusher press of one bracelet | BleScanner.startScanForPusherEvent | BleScanEvent.BleScanResults.results in the scan listener |
| The connection state | BleDevice.connectionState | Property (ConnectionState); changes in DeviceConnectionStateListener.onWatchConnectionStateChanged |
| The bond (pairing) state | BleDevice.bondState | Property (BondState); changes in DeviceBondStateListener.onBondStateChanged |
| Whether the bracelet accepts commands | BleDevice.isInitialized | Property; see Bracelet Initialization |
| The bracelets this phone used before | BleSdk.getInstance().getRecentDevices() | Return value (List<BleDeviceInfo>) |
The SDK calls the connection, bond and notification listeners on its callback scheduler. This is the main thread unless you set another one with CorsanoSdkConfig.Builder().callbackScheduler(...).
Scanning and connecting to bracelet
Preparing for BLE scan
The first step is to check that everything is ready for a BLE scan.
Checking Bluetooth state
Bluetooth must be on before you scan or connect. While Bluetooth is off, startScan and startScanForPusherEvent throw IllegalStateException (from SDK 3.0.0; they threw NullPointerException before). So check the Bluetooth state first.
import com.corsano.sdk.ble.util.BluetoothUtil
if (!BluetoothUtil.isBluetoothSupported()) {
// show a "Bluetooth not supported" screen
return
}
if (!BluetoothUtil.isBluetoothEnabled()) {
// ask the user to turn Bluetooth on
val intent = BluetoothUtil.getEnableBluetoothIntent()
fragment.startActivity(intent)
}
You can read the Bluetooth state at any moment. We recommend that you also listen to its changes:
val bluetooth = BleSdk.getInstance().getBluetooth()
val listener = object : Bluetooth.StateListener {
override fun onBluetoothStateChanged(state: BluetoothState) {
// handle the state change here
}
}
bluetooth.addStateListener(listener)
// when you no longer need it
bluetooth.removeStateListener(listener)
BluetoothState has the values NOT_SUPPORTED, TURNED_OFF, TURNING_ON, TURNED_ON and TURNING_OFF. Bluetooth also has isSupported(), isBluetoothEnabled() and getState().
Getting Scanner
To look for bracelets you need the BleScanner. There is one scanner; getScanner() always returns the same instance.
// get BleSdk instance
val bleSdk = BleSdk.getInstance()
// get BleScanner instance
val scanner = bleSdk.getScanner()
Requesting runtime permissions
The SDK's manifest declares the Bluetooth and location permissions, so you do not add them to your own manifest. Your app must still ask the user for the runtime permissions before it scans and before it connects. The SDK does not ask for them and does not check them in startScan.
| Android version | Permissions to scan (BleScanner.getRequiredPermissions()) | Permissions to connect (BleDevice.getConnectPermissions()) |
|---|---|---|
| Android 5.x | None | None |
| Android 6 to 8.1 | ACCESS_COARSE_LOCATION | None |
| Android 9 to 11 | ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION | None |
| Android 12 and later | ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, BLUETOOTH_SCAN, BLUETOOTH_CONNECT | BLUETOOTH_CONNECT |
You do not need to check the Android version yourself. BleScanner.getMissingPermissions() and BleDevice.getMissingConnectPermissions() return the permissions that the user has not granted yet. An empty list means that you can go on.
// in a Fragment or an Activity
private val scanPermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
if (results.values.all { granted -> granted }) startScan()
}
fun checkPermissionsAndScan() {
val missing = scanner.getMissingPermissions()
if (missing.isEmpty()) startScan() else scanPermissions.launch(missing.toTypedArray())
}
The Data module also declares POST_NOTIFICATIONS. The sample app asks for it at start on Android 13 and later (MainActivity.kt).
Performing BLE scan
startScan reports what happens to its listener as BleScanEvent objects. Stop the scan with stopScan().
val scanner = BleSdk.getInstance().getScanner()
// start scan
scanner.startScan { event ->
// handle event here
}
// stop scan
scanner.stopScan()
By default the scan reports Corsano bracelets only: ScanDeviceType.BRACELET_B1 (287-1B), BRACELET_B2 (287-2B) and bracelets whose firmware update was interrupted (BRACELET_1B_NEED_RECOVERY, BRACELET_2B_NEED_RECOVERY, see DFU recovery). To choose the types yourself, pass them as the first argument: scanner.startScan(arrayListOf(ScanDeviceType.BRACELET_B2)) { event -> }. A list that contains ScanDeviceType.OTHER scans without a filter and reports every BLE device.
Rules of the scanner:
- Only one scan runs at a time.
startScanandstartScanForPusherEventthrowIllegalStateExceptionwhilescanner.isScanning()istrue. - A scan has no timeout. It runs until you stop it. Stop it after a reasonable time and only scan while your app is in the foreground, to save the phone's battery.
- If the SDK is locked by its licence check, no scan starts and the listener gets
BleScanFailed(BleScanFailed.LICENCE_LOCKED)at once. See Licence Key.
Scan events
| Event | Description |
|---|---|
BleScanStarted | The scan started. Sent once, during the startScan call. |
BleScanResults | One or more devices were found. results is a list of BleScanRecord. The same device is reported many times during a scan. |
BleScanStopped | The scan was stopped by stopScan(). Sent once. |
BleScanFailed | The scan did not start or stopped with an error. errorCode is Android's ScanCallback.SCAN_FAILED_* code, or BleScanFailed.LICENCE_LOCKED (-32, from SDK 3.0.0) when the SDK is locked by its licence check. |
After a BleScanFailed with an Android error code, call stopScan() before you start a new scan. The scanner still counts the failed scan as running.
A BleScanRecord has these fields:
| Field | Type | Description |
|---|---|---|
address | String | The Bluetooth address. Pass it to getDevice(address). |
name | String? | The Bluetooth name. Can be empty. |
rssi | Int | The signal strength of this advertisement. |
scanType | ScanDeviceType | BRACELET_B1, BRACELET_B2, BRACELET_1B_NEED_RECOVERY, BRACELET_2B_NEED_RECOVERY or OTHER. |
advertisementData | AdvertisementData? | isPusherPressed, serialNumber, hardwareId, modelId and brandId. null for a bracelet that needs recovery and for other devices. |
During the scan, keep one record per address:
var foundDevices = emptyList<BleScanRecord>()
scanner.startScan { event ->
when (event) {
is BleScanEvent.BleScanResults -> {
foundDevices = (event.results + foundDevices).distinctBy { it.address }
}
is BleScanEvent.BleScanFailed -> {
// event.errorCode
}
BleScanEvent.BleScanStarted -> { /* show a progress indicator */ }
BleScanEvent.BleScanStopped -> { /* hide it */ }
}
}
Pairing with bracelet
Detecting Pusher event
Mandatory starting SDK 0.8.7
Before pairing and connecting to the bracelet for the first time, a user action is necessary for security: a pusher press.
- B1: push on the pusher button.
- B2: it has no pusher button. The equivalent is to put the bracelet on the charger and take it off the charger.
The bracelet reports the press in its advertisement data (AdvertisementData.isPusherPressed).
After the first scan, stop it and start a second scan that waits for the pusher press of the chosen bracelet:
val scanner = BleSdk.getInstance().getScanner()
// start scan
scanner.startScanForPusherEvent(macAddress) { event ->
if (event is BleScanEvent.BleScanResults) {
val bracelet = event.results.firstOrNull { it.address == macAddress }
if (bracelet != null) {
scanner.stopScanForPusherPress()
// start pairing: connect to the bracelet
}
}
}
// stop scan (also when the user gives up)
scanner.stopScanForPusherPress()
Stop this scan with stopScanForPusherPress(), not with stopScan(). stopScan() only ends a scan that startScan started.
Scan for pusher press events
| Event | Description |
|---|---|
BleScanStarted | The scan started. Sent once, during the startScanForPusherEvent call. |
BleScanResults | A bracelet whose pusher was pressed was found. This scan reports no other records. Check that address is the address you asked for, as the example above does. |
BleScanStopped | The scan was stopped by stopScanForPusherPress(). Sent once. |
BleScanFailed | The scan did not start or stopped with an error. Same codes as for startScan. |
This scan has no timeout either. The sample app stops it after 30 seconds (WatchScanVerifyViewModel.kt).
You can also read the pusher press from the records of a normal scan:
val targetDevice = foundDevices.find {
it.advertisementData?.isPusherPressed == true
}
if (targetDevice != null) {
// start pairing process
}
Connecting to bracelet
You connect to the bracelet by the address you got from the scan. The first connection also starts the pairing.
Get the BleDevice, check the permission and call connect():
val address = "..."
// get a device by address
val device = BleSdk.getInstance().getDevice(address)
// check permissions
val permissions = device.getMissingConnectPermissions()
if (permissions.isEmpty()) {
// connect to device
device.connect(keepAlive = true)
} else {
// request the permissions, then call connect
}
BleSdk.getDevice(address) keeps the BleDevice in a pool. You can call it as often as you like: it returns the same instance until you call removeDevice(address).
connect returns at once. The connection is made in the background, so listen to the connection state to know when it is ready.
Getting device status
enum class ConnectionState {
NOT_CONNECTED,
DISCONNECTING,
CONNECTING,
CONNECTED
}
Read the current state from device.connectionState (in the sample app: DeviceManager.getCurrentDevice()?.connectionState), or listen to the changes with BleDevice.addConnectionStateListener():
val connectionListener = object : BleDevice.DeviceConnectionStateListener {
override fun onWatchConnectionStateChanged(state: ConnectionState) {
if (state == ConnectionState.CONNECTED) {
// the link is up
}
}
}
device.addConnectionStateListener(connectionListener)
// when you no longer need it
device.removeConnectionStateListener(connectionListener)
| State | Meaning |
|---|---|
NOT_CONNECTED | No link, and no attempt is running. With keepAlive, the SDK may be waiting to try again. |
CONNECTING | An attempt is running: Android connects, then the SDK discovers the services and turns the bracelet's notifications on. |
CONNECTED | The link is up. Commands can run once the bracelet is bonded and initialized. |
DISCONNECTING | disconnect() was called and the link is closing. |
If your app uses coroutines and the data module, device.connectionStateFlow() and device.bondStateFlow() (com.corsano.sdk.data.util) give the same values as a Flow. They emit the current value first.
The keepAlive flag and reconnection
The keepAlive flag decides whether the SDK brings the connection back by itself. Use true in normal use. Use false only if you want to manage the connection yourself.
From SDK 3.0.0 a connection behaves as follows:
| Situation | With keepAlive = true | With keepAlive = false |
|---|---|---|
| A connection attempt does not complete in 45 seconds, or Android reports that it failed | The state goes to NOT_CONNECTED. The SDK tries again at the moment the 45 seconds of the failed attempt end, and repeats this until the bracelet is connected. | The state goes to NOT_CONNECTED. Call connect again. |
| The link is lost while connected | The SDK reconnects at once. The state goes to CONNECTING straight away. | The state goes to NOT_CONNECTED. Call connect again. |
| Bluetooth is turned off | The state goes to NOT_CONNECTED. The SDK connects again when Bluetooth is turned on. | The state goes to NOT_CONNECTED. |
Other rules:
connectdoes nothing while the bracelet is connected or while an attempt is running. If the running attempt has been stuck for more than 60 seconds,connectstops it and starts a new one.- From Android 12,
connectwithout theBLUETOOTH_CONNECTpermission opens no connection and the state staysNOT_CONNECTED. It does not throw. Callconnectagain when the user has granted the permission. The user can take the permission away at any time, so checkgetMissingConnectPermissions()before everyconnect. - If the SDK is locked by its licence check,
connectopens no connection and a lost link is not reconnected. See Licence Key. - When a command gets no answer from the bracelet within its timeout, the SDK disconnects and connects again with
keepAlive = true. See BLE SDK. device.keepAlivereturns the value in use.
Several bracelets can be connected at the same time. The limit depends on the phone and the Android version.
Pairing with bracelet
Commands need a bond between the phone and the bracelet. This is also called "pairing". You do not start it yourself: when a connection comes up and Android has no bond for the bracelet yet, the SDK asks Android to create one.
The connection reports CONNECTED before the bond exists. Commands that you send in the meantime wait in the queue and run when the bond state is BONDED.
BondState has the values NOT_BONDED, BONDING and BONDED. You can read the current bond state or observe its changes for a particular device:
val watch = BleSdk.getInstance().getDevice(address)
if (watch.bondState == BondState.BONDED) {
// do something
}
watch.addBondStateListener(
object : BleDevice.DeviceBondStateListener {
override fun onBondStateChanged(state: BondState) {
// do something
}
}
)
Alternatively, you can subscribe to bond state updates for all devices:
val bluetooth = BleSdk.getInstance().getBluetooth()
bluetooth.addBondStateListener(
object : Bluetooth.BondStateListener {
override fun onBondStateChanged(address: String, state: BondState) {
// do something
}
}
)
From Android 12 Android only gives the bond state to an app that holds the BLUETOOTH_CONNECT permission. A device that you get with getDevice without this permission reports NOT_BONDED.
The bracelet is ready for your commands when all three are true: connectionState == CONNECTED, bondState == BONDED and isInitialized == true. The simplest way to wait for this is ensureInitialized, see Bracelet Initialization.
Disconnecting
To disconnect, call device.disconnect(). Call this when you have finished working with the bracelet.
disconnect()also setskeepAlivetofalse, so the SDK does not reconnect.- The state goes to
DISCONNECTINGand then toNOT_CONNECTED. If the link has not closed after 15 seconds, the SDK closes it itself. - The command that is running and the commands that are waiting for this bracelet end with an error (
"Watch disconnected") in theironErroror in their failedResult.
Unpair
To unpair a bracelet, stop its data transfer first and then remove the device:
fun unpair(context: Context, address: String) {
// 1. Stop the automatic data transfer and the background work for this bracelet
DataSdk.getInstance().getDownloadManager().stopAll(
context,
address = address,
onSuccess = { },
onError = { }
)
// 2. Disconnect, remove the Android bond and forget the device
val removed: Boolean = BleSdk.getInstance().removeDevice(address, removeFromRecents = true)
}
removeDevice disconnects the bracelet, removes the Android bond and removes the device from the SDK's pool. It returns true when the bracelet is unpaired (or was not paired), and false when it could not unpair, for example because Bluetooth is off. With removeFromRecents = true the device also leaves the list of getRecentDevices(). The default is false.
The sample app does the same with its helper:
fun unpair(context: Context) {
DeviceManager.getCurrentDevice()?.let {
DataSdk.getInstance().getDownloadManager().stopAll(context,
address = it.address,
onSuccess = { },
onError = { }
)
}
DeviceManager.clearCurrentDevice(unpair = true)
}
Check the Sample app in the class WatchFragmentViewModel.kt
Bracelets used before
BleSdk.getInstance().getRecentDevices() returns the bracelets that your app got with getDevice, in no particular order, as BleDeviceInfo(address, name, isBonded). The list is empty while Bluetooth is off or while a scan permission is missing.
Next step: set up the bracelet