来自iOS开发背景,当使用蓝牙LE充当外围设备时,您可以在“中央”BLE设备订阅(启用通知)特征时注册回调。
我很难看到如何在Android上实现这一目标。 如果你正在使用蓝牙LE作为中心,我可以看到你如何订阅: bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);
这与iOS上的相同: peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)
现在,在iOS上调用上面的内容之后,在外围端你得到一个回调,说中央已经订阅了类似于: peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic) ,然后它为你提供了对订阅的设备的引用/启用通知和什么特征。
什么是Android上的等价物?
为清楚起见,我将指出我不需要在Android上订阅特性,该设备充当外围设备,并且需要在其他设备订阅特性时得到通知。
很抱歉,如果这很明显,但我无法在文档或其他地方find它。
在设定赏金之后,我有了一个想法,哈哈应该等一下,让我的大脑有更多时间思考;)
似乎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, "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(这是告诉远程需要发送通知的步骤)。