我正在创建一个应用程序,它定期(假设每隔5秒)通过BE扫描,在屏幕上向用户显示他周围的设备数量. 我们还假设用户已接受所有权限.
以下是代码的一个示例:
class ExampleBle(private val viewModel: Mainviewmodel) {
private val deviceAddresses = arrayListOf<String>()
private val bleAdapter: BluetoothAdapter by lazy {
val b = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
b.adapter
}
private val bleScan : BluetoothLeScanner by lazy {
bleAdapter.bluetoothLeScanner
}
private val scanSettings = ScanSettings.Builder()
//Questo tipo di scan è usato per scan di lunga durata e spreca meno energia
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
private val scanCallback = object : ScanCallback() {
@SuppressLint("MissingPermission")
override fun onScanResult(callbackType: Int, result: ScanResult) {
deviceAddresses.add(result.device.address)
}
override fun onScanFailed(errorCode: Int) {
Log.e("ScanCallback", "onScanFailed: code $errorCode")
}
}
//function to repeat every 5 seconds
fun startScan(){
bleScan.startScan(null, scanSettings, scanCallback)
// at this point the deviceAddresses list contains the addresses
// of all the devices around
viewModel.updateNumberDevices(deviceAddresses.size)
//clear the list to recollect all the device addresses from the next scan after 5 seconds
deviceAddresses.clear()
}
}
因此,基本上,如果用户周围有10台设备: StartScan()->;bleScan.startScan() ->;scanCallBack->;{deviceAddresse.add(Result.device1.Address)} . . . ->;scanCallBack->;{deviceAddresses.add(result.device10.address)}
代码是否与我想要实现的目标一致? 我也有一些疑问:
- 如果周围有许多设备(例如100台),扫描是否能够在5秒内返回所有地址?
- 如果它没有成功,并且我在前一个函数完成之前启动了bleStartScan函数,我正在更新的列表中是否会有一些不规范的地方(例如重复的地址等)?
我希望我已经很好地解释了我的意思,我没有举一个太"粗暴"的例子. 我只是想以非常直接和基本的方式了解BE扫描是如何在更实际的水平上工作的.