如何知道 BLE 设备何时订阅 Android 上的特征?

How to know when a BLE device subscribes to a characteristic on Android?

来自 iOS 开发背景,当使用蓝牙 LE 作为外围设备时,您可以在 "central" BLE 设备订阅(启用通知)特性时注册回调。

我正在努力了解如何在 Android 上实现这一点。如果您使用蓝牙 LE 作为中心,我可以看到您会如何订阅: bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

这与 iOS 上的相同: peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)

现在,在 iOS 上调用上面的方法后,在外围设备端你会收到一个回调,说明中央设备已使用类似于以下的方法进行订阅: peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic) 然后为您提供对 subscribed/enabled 通知的设备及其特征的参考。

Android 的等效项是什么?

为清楚起见,我会指出我不需要订阅 Android 上的特征,该设备充当外围设备,需要在其他设备订阅特征时得到通知。

很抱歉,如果这很明显,但我无法在文档或其他地方找到它。

设置赏金后我有一个想法,哈哈应该再等一下,让我的大脑有更多时间思考;)

iOS 似乎抽象了一点订阅的内部工作方式。在 ios CoreBluetooth 引擎盖下,某个 "Descriptor" 特征由中心写入,这表明中心想要订阅该特征的值。

这是您需要添加到 BluetoothGattServerCallback 子类的代码:

    @Override
    public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
        super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);

        Log.i(TAG, "onDescriptorWriteRequest, uuid: " + descriptor.getUuid());

        if (descriptor.getUuid().equals(Descriptor.CLIENT_CHARACTERISTIC_CONFIGURATION) && descriptor.getValue().equals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {
            Log.i(TAG, "its a subscription!!!!");

            for (int i = 0; i < 30; i++) {
                descriptor.getCharacteristic().setValue(String.format("new value: %d", i));
                mGattServer.notifyCharacteristicChanged(device, descriptor.getCharacteristic(), false);
            }
        }
    }

最好使用 https://github.com/movisens/SmartGattLib 作为 uuid(Descriptor.CLIENT_CHARACTERISTIC_CONFIGURATION 但原始值是 00002902-0000-1000-8000-00805f9b34fb

同意@stefreak

并且,

bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

对远程设备没有做任何事情,这个API只是改变了本地蓝牙堆栈的一个通知位,即如果外设向本地发送通知,本地堆栈将判断应用程序是否已经注册了这个通知,如果是,否则转移到应用程序,忽略它。

所以除了 setCharacteristicNotification 你还应该需要 writeDescriptor 用于你注册的通知(这是告诉远程需要发送通知的步骤)。