在 Android BLE 中处理指示而不是通知

Handling indications instead of notifications in Android BLE

使用蓝牙 SIG 应用程序加速器代码,它很好地展示了蓝牙低功耗的不同概念。但是,它没有提及与通知相对的指示。我知道与通知不同,需要确认指示,在代码中我会做 byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE : BluetoothGattDescriptor.DISABLE_INDICATION_VALUE; 而不是 byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;。还有什么我需要做的吗?我究竟如何让服务器知道我收到了所需的指示?我需要添加什么吗?

@Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic)
        {

            notification_id++;
            Log.d("BleWrapper","notification count = " + notification_id);
            // characteristic's value was updated due to enabled notification, lets get this value
            // the value itself will be reported to the UI inside getCharacteristicValue
            getCharacteristicValue(characteristic);
            // also, notify UI that notification are enabled for particular characteristic
            mUiCallback.uiGotNotification(mBluetoothGatt, mBluetoothDevice, mBluetoothSelectedService, characteristic);
        }

你描述的已经足够了,但有一点错误。

确实,BLE 指示需要客户端确认,而通知则不需要。然而,这完全由 Android 在幕后处理。当您的 onCharacteristicChanged 回调被调用时,系统会确认指示。

您已经发现的唯一区别是您需要在 BLE 服务器上的客户端特征配置描述符中启用正确的标志。对于常规通知,请使用 ENABLE_NOTIFICATION_VALUE。对于适应症,请使用 ENABLE_INDICATION_VALUE。请注意,您通过编写 DISABLE_NOTIFICATION_VALUE 来禁用 both。根据文档,您提到的 DISABLE_INDICATION_VALUE 不存在!

在Android方面,在enable = true处使用BluetoothGatt#setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable)就足够了。这将适用于通知和指示。在这两种情况下,都会使用您的 onCharacteristicChanged 回调。

(你现在可能已经想通了,但无论如何发帖以防有人通过 Google 来到这里。)