如何知道 BLE 设备何时订阅了 Android 上的某个特性?

问题描述 投票:0回答:2

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

我正在努力了解这是如何在 Android 上实现的。如果您使用蓝牙 LE 作为中心,我可以看看您如何订阅:

bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

这与 iOS 上的相同:

peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)

现在,在 iOS 上调用上述内容后,在外围设备端,您会收到一个回调,表明中央设备已订阅,方法类似于:

peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic)
然后为您提供订阅/启用通知的设备及其特征的参考。

Android 上的等效项是什么?

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

抱歉,如果这是显而易见的,但我在文档或其他地方找不到它。

java android bluetooth-lowenergy
2个回答
8
投票

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

iOS 似乎已经抽象了一些订阅的内部工作方式。在 ios CoreBluetooth 引擎盖下,中心编写了某个特征的“描述符”,这表明中心想要订阅该特征的值。

这是您需要添加到

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, "it's 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


3
投票

同意@stefreak

并且,

bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

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

因此,除了 setCharacteristicNotification 之外,您还应该需要 writeDescriptor 来注册通知(这是告诉远程需要发送通知的步骤)。

© www.soinside.com 2019 - 2024. All rights reserved.