Kotlin Android BLE using nordicsemi cannot get BLE devices

205 views Asked by At

I cannot get BLE devices.

For scan devices, I use no.nordicsemi.android.kotlin.ble:scanner:1.0.6

I call startBleScanning in the ViewModel.

Code:

val btDevicesLiveData = MutableLiveData<List<String>>()
private val aggregator = BleScanResultAggregator()

fun startBleScanning(context: Context) {
    BleScanner(context).scan()
        .map { aggregator.aggregateDevices(it) }
        .onEach {
            btDevicesLiveData.postValue(it.map { device ->
                Log.d("BT", "result: ${device.address}")
            })
        }
        .launchIn(viewModelScope)
}

In log, I see paired devices only.

Bluetooth on my phone is enabled. The device is enabled too.

How can I get BLE devices?

1

There are 1 answers

2
Ivo Zivkov On

You can add custom settings when you execute the scan function:

A BleScannerSettings instance has this structure:

  • scanMode Set scan mode ([BleScanMode]) for Bluetooth LE scan.
  • reportDelay Set report delay timestamp for Bluetooth LE scan.
  • includeStoredBondedDevices Flag indicating weather to include stored bonded devices in scan result.
  • callbackType Set callback type ([BleScannerCallbackType]) for Bluetooth LE scan.
  • numOfMatches Set the number of matches ([BleNumOfMatches]) for Bluetooth LE scan filters hardware match.
  • matchMode Set match mode ([BleScannerMatchMode]) for Bluetooth LE scan filters hardware match.
  • legacy Set whether only legacy advertisements should be returned in scan results.
  • phy Set the Physical Layer ([BleScannerPhy]) to use during this scan.
val btDevicesLiveData = MutableLiveData<List<String>>()
private val aggregator = BleScanResultAggregator()

val custom = BleScannerSettings(
    ...
    includeStoredBondedDevices = false,
    ...
)

fun startBleScanning(context: Context) {
    BleScanner(context).scan(settings = custom)
        .map { aggregator.aggregateDevices(it) }
        .onEach {
            btDevicesLiveData.postValue(it.map { device ->
                Log.d("BT", "result: ${device.address}")
            })
        }
        .launchIn(viewModelScope)
}

Probably you are using legacy devices or you need to check the scan mode by default is BleScanMode.SCAN_MODE_LOW_POWER