簡體   English   中英

如何知道BLE設備何時訂閱Android上的特性?

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

來自iOS開發背景,當使用藍牙LE充當外圍設備時,您可以在“中央”BLE設備訂閱(啟用通知)特征時注冊回調。

我很難看到如何在Android上實現這一目標。 如果您正在使用Bluetooth LE作為中心,我可以看到您的訂閱方式: bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

這與iOS上的相同: peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)

現在,在iOS上調用上面的內容之后,在外圍端你會得到一個回調,說中央已經訂閱了類似於: peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic) ,然后它會為你提供訂閱的設備的引用/啟用通知和什么特征。

什么是Android上的等價物?

為清楚起見,我將指出我不需要在Android上訂閱特性,該設備充當外圍設備,並且需要在其他設備訂閱特性時得到通知。

很抱歉,如果這很明顯,但我無法在文檔或其他地方找到它。

在設定賞金之后,我有了一個想法,哈哈應該等一下,讓我的大腦有更多時間思考;)

似乎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(這是告訴遠程需要發送通知的步驟)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM