BLE扫描第二次找不到设备

时间:2020-04-10 10:36:52

标签: android kotlin bluetooth-lowenergy

我正在实现BLE应用程序,并且第一次扫描可以正常进行。我发现我执行了一些写操作的设备并且断开了连接。然后,第二次尝试查找设备时,我的扫描未返回该设备,因此我找不到问题。这是我的代码:

扫描操作:

fun scanForBluetoothLamps(bluetoothAdapter: BluetoothAdapter, scanCallback: ScanCallback) {
    val uuid = ParcelUuid(convertIntegerToUUID(LIGHT_SERVICE))
    val filter = ScanFilter.Builder().setServiceUuid(uuid).build()
    val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
            .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE).build()

    bluetoothAdapter.bluetoothLeScanner.startScan(listOf(filter), settings, scanCallback)
    Handler().postDelayed({
        bluetoothAdapter.bluetoothLeScanner.stopScan(scanCallback)
        _event.postValue(false)
    }, SCAN_TIME)
}

我将该操作称为活动:

private val scanOperation = ScanOperation()

fun setupAdapter(){
scanButton.setOnClickListener{
 scanOperation.scanForBluetoothLamps(bluetoothAdapter, viewModel.scanCallback)
 }
}

在ViewModel中,我有我的scanCallback:

val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        result?.let {
            if (!btDevicesList.contains(result.device)) {
                btDevicesList.add(result.device)
            }
        }
    }

    override fun onBatchScanResults(results: MutableList<ScanResult>?) {
        results?.forEach { result ->
            if (!btDevicesList.contains(result.device)) {
                btDevicesList.add(result.device)
            }
        }
    }
}

这是我在断开设备连接之前调用的断开连接功能

fun disconnect(gatt: BluetoothGatt?) {
    gatt?.run {
        disconnect()
        close()
    }
}

1 个答案:

答案 0 :(得分:0)

似乎您没有在两次扫描之间清除btDevicesList。因此,第二次忽略该设备。