首页 > 解决方案 > Android 蓝牙外设模式通知描述符

问题描述

我正在编写一个类似于 BLE 外围设备的 Android 应用程序。

我的onDescriptorWriteRequest override派生BluetoothGattServerCallback类中有 。

当我notifications从一个IOS名为 LightBlue 的应用程序订阅时,会调用此方法,但我似乎找不到任何方法来判断它是传入ENABLE_NOTIFICATION_VALUE还是DISABLE_NOTIFICATION_VALUE.

我找到了一些我基于此部分的代码,他们使用description.getValue()并将其与这些常量进行比较。

就我而言getValue() returns null,无论我选择什么。

value 参数onDescriptorWriteRequest()有一个值,但它是一个long值,每次只有一部分更改为看似随机的东西,所以我无法确定哪个会启用,哪个会禁用,如果这实际上是什么值用于。它具有像[B@633adb and [B@690f978.

这是我正在使用的代码:

        @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(UUID.fromString(notificationDescriptionUUID))) {
            if (descriptor.getValue().equals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {

                // this is how I keep track of which devices to notify later
                removeDeviceFromNotifyList(notifyDeviceList, device);
                notifyDeviceList.add(device);
            }
            else if (descriptor.getValue().equals(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) {

                // this is how I keep track of which devices to notify later
                removeDeviceFromNotifyList(notifyDeviceList, device);
            }
        }

        // now tell the connected device that this was all successfull
        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
    }

现在它崩溃了,descriptor.getValue().equals因为getValue()is always null

任何帮助,将不胜感激。

标签: androidbluetoothnotifications

解决方案


onDescriptorWriteRequest当中央想要为描述符分配值时调用该函数。假设您的目标是通过检查BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE或 来检查中央是否要订阅/取消订阅BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE

为此,只需检查value参数是否等于这些预定义常量中的任何一个。代码可以如下 -

if ( Arrays.equals(value, BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE))
{
 //Your disable code 
}
else if (Arrays.equals(value, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE))
{
//Your enable code
}

我没有测试过这段代码。但我相信这应该有效。


推荐阅读