2016-03-24 84 views
7

从iOS开发背景来看,使用蓝牙LE作为外设时,您可以在“中央”BLE设备为特性订阅(启用通知)时注册回调。如何知道BLE设备何时订阅Android上的特征?

我很努力地看到这是如何在Android上实现的。如果你正在使用蓝牙LE作为中心工作,我可以看到你如何订阅: bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

这是相同的,因为这在iOS上:现在 peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)

,呼吁上述后在外围设备上,您可以通过类似于: peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic)的方法获得中央订购的回电,然后为您提供订阅/启用通知的设备的参考信息以及具体的参数。

Android上的等效物是什么?

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

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

+0

你需要类似回调的东西吗?不确定是什么问题? –

+1

对不起,如果不是,但我认为我很清楚,我需要某种方式知道设备订阅。如果这是通过回调很好,但我只需要知道如何获得这些信息。这是iOS上的一个回调,因此这是我作为示例的唯一参考。 –

+0

@ kanecheshire你找到了什么?需要相同的 – stefreak

回答

6

只需设置赏金我有一个主意,哈哈应该已经等了多一点给我的大脑有更多的时间去思考;)

看来,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

+0

啊,这看起来不错。我会试试这个!抱歉,花了这么长的时间回复,奇怪的是一段时间没有在SO上:/ –

+0

np开心如果它在这几个月后仍然有帮助 – stefreak

+1

虽然我还没有机会尝试这个,但这篇文章看起来似乎以关联你上面发布的内容:http://nilhcem.com/android-things/bluetooth-low-energy –

3

与@同意stefreak

,并

bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true); 

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

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

+0

我也注意到你需要在服务器端添加这个特性才能工作:'BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString(“00002902-0000-1000-8000-00805f9b34fb”),BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE); beaconCharacteristic.addDescriptor(descriptor); service.addCharacteristic(beaconCharacteristic);' – stefreak

+0

正确。 Gatt服务器还需要判断描述符的值来决定是否发送通知。不过我认为android API的命名有时并不合理...... –

相关问题