在 Android 上收到重复的 BLE 通知

Getting duplicate BLE notifications on Android

我正在使用 BLE 协议开发 nRF52840 和 Android 智能手机之间的帧交换序列。

第一次连接时,一切正常。 我使用以下方法激活 Android 智能手机对 BLE 通知的监听:

    fun enableBleNotificationsOnCentral(currentBluetoothGatt: BluetoothGatt, serviceUUID: UUID, characteristicUUID: UUID) {
        getMainDeviceService(currentBluetoothGatt, serviceUUID)?.let { service ->
            val notificationConfiguration = service.getCharacteristic(characteristicUUID)
            val result = currentBluetoothGatt.setCharacteristicNotification(notificationConfiguration, true)

            println(result)
        }
    }

并且我使用这种方法在 nRF52840 上启用了发送 BLE 通知:

    fun enableBleNotificationsOnPeripheral(currentBluetoothGatt: BluetoothGatt, serviceUUID: UUID, characteristicUUID: UUID, descriptorUUID: UUID) {
        getMainDeviceService(currentBluetoothGatt, serviceUUID)?.let { service ->
            val descriptorConfiguration = service.getCharacteristic(characteristicUUID).getDescriptor(
                descriptorUUID).apply {
                value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
            }
            val result = currentBluetoothGatt.writeDescriptor(descriptorConfiguration)

            println(result)
        }
    }

每次我的智能手机连接到 nRF52840 时都会调用这些方法。

但是如果我断开连接并再次连接,我会收到一式两份的通知。 此外,如果我第 3 次断开连接并重新连接,我会收到 3 次通知,每次重新连接时都会收到一次通知。

我在 nRF52840 上检查了我的代码,它没有重复通知。

这是我请求断开连接时调用的方法:

private fun disconnectFromCurrentDevice() {
    currentBluetoothGatt?.disconnect()
    BLECallbackManager.currentDevice = null
    setUiMode(false)
}

我想我的问题与以下事实有关:当我断开连接时,我没有禁用我的 Android 应用程序接收 BLE 通知,但我不确定。如果那是问题的来源,我应该什么时候在 disconnect 方法中进行?你能帮帮我吗?

我猜你正在为每次新的连接尝试创建一个新的 BluetoothGatt 对象,但你没有破坏前一个。

尝试将 disconnect() 更改为 close()