我构建了一个应用程序,该应用程序不断检查 BLE 设备,并在 onScanResult 上更新新发现的设备的列表。
如果在一定时间内没有找到设备,我想删除列表中的设备。如果是这种情况,是否有一种优雅的方法来获取回调(我试图避免一些令人讨厌的解决方法)?在 developer.android.com 的文档中我没有找到类似的东西。方法:
private val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
val device = result.device
Log.d("LeDeviceScanner", "Device found: ${device.address} - ${device.name ?: "Unknown"}")
onDeviceResult(result.device)
}
}
据我所知,其他回调:onScanFailed和onBatchScanResults,这些都对我没有帮助。
我将回答我自己的问题,希望对某人有所帮助。 没有找到设备的简单回调。因此必须找到解决方法。 就我而言,我将找到的设备存储在列表中,如果在一分钟的搜索中没有再次找到该设备,则希望删除该设备。我使用每次找到设备时传回的时间戳来完成此操作。不是那么优雅,但它有效。
要从列表中删除扫描过程中不再可用的蓝牙设备,您可以实现计时器机制,如果在指定时间窗口内没有找到新设备,则清除列表。您可以通过以下方式修改代码来实现此目的:
private var scanTimer: CountDownTimer? = null
private val scanDurationMillis = 12000 // 12 seconds
private var _bleDeviceList = MutableLiveData<List<BluetoothDevice>>()
private fun startScanTimer() {
scanTimer?.cancel() // Cancel any existing timer
scanTimer = object : CountDownTimer(scanDurationMillis.toLong(), scanDurationMillis.toLong()) {
override fun onTick(millisUntilFinished: Long) {
// Not needed for this timer
}
override fun onFinish() {
clearDeviceList()
}
}
scanTimer?.start()
}
private fun restartScanTimer() {
scanTimer?.cancel()
startScanTimer()
}
private fun clearDeviceList() {
_bleDeviceList.value = emptyList()
Log.d("BluetoothConnectionViewModel", "Device list cleared")
}
现在在 onScanResult 中调用 restartScanTimer() 方法
override fun onScanResult(callbackType: Int, result: ScanResult) {
// Your code is here
restartScanTimer()
}