75

用于测试的设备:Nexus 4、Android 4.3

连接工作正常,但onCharacteristicChanged我的回调方法从未被调用。但是,我正在使用setCharacteristicNotification(char, true)inside注册通知onServicesDiscovered,该函数甚至返回 true。

设备日志(当通知应该出现/通过蓝牙设备发送时实际上根本没有消息):

07-28 18:15:06.936  16777-16809/de.ffuf.leica.sketch D/BluetoothGatt: setCharacteristicNotification() - uuid: 3ab10101-f831-4395-b29d-570977d5bf94 enable: true
07-28 18:15:06.936    4372-7645/com.android.bluetooth D/BtGatt.GattService: registerForNotification() - address=C9:79:25:34:19:6C enable: true
07-28 18:15:06.936    4372-7645/com.android.bluetooth D/BtGatt.btif: btif_gattc_reg_for_notification
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1018
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.GattService: onRegisterForNotifications() - address=null, status=0, registered=1, charUuid=3ab10101-f831-4395-b29d-570977d5bf94
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1016
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1018
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.GattService: onRegisterForNotifications() - address=null, status=0, registered=1, charUuid=3ab10102-f831-4395-b29d-570977d5bf94
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1016
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1013
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1013
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.976    4372-7645/com.android.bluetooth D/BtGatt.btif: btif_gattc_upstreams_evt: Event 9

GATT 通知在 iOS 上运行良好,该应用程序与 Android 上的基本相同(注册通知等)。

有没有其他人经历过这个可能的解决方案?

4

10 回答 10

86

您似乎忘记编写告诉您的 BLE 设备进入此模式的描述符。请参阅http://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification处处理描述符的代码行

如果不设置此描述符,您将永远不会收到对特征的更新。打电话setCharacteristicNotification是不够的。这是一个常见的错误。

代码被剪断

protected static final UUID CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");

public boolean setCharacteristicNotification(BluetoothDevice device, UUID serviceUuid, UUID characteristicUuid,
        boolean enable) {
    if (IS_DEBUG)
        Log.d(TAG, "setCharacteristicNotification(device=" + device.getName() + device.getAddress() + ", UUID="
                + characteristicUuid + ", enable=" + enable + " )");
    BluetoothGatt gatt = mGattInstances.get(device.getAddress()); //I just hold the gatt instances I got from connect in this HashMap
    BluetoothGattCharacteristic characteristic = gatt.getService(serviceUuid).getCharacteristic(characteristicUuid);
    gatt.setCharacteristicNotification(characteristic, enable);
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID);
    descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[] { 0x00, 0x00 });
    return gatt.writeDescriptor(descriptor); //descriptor write operation successfully started? 
}
于 2013-08-02T08:11:45.940 回答
42

@Boni2k - 我有同样的问题。就我而言,我有 3 个通知特征和一些读/写特征。

我确实发现writeGattDescriptorand之间存在一些依赖关系readCharacteristic。 在您发出任何 readCharacteristic 调用之前,所有writeGattDescriptor必须先出现并完成。

这是我使用的解决方案Queues。现在我收到通知,其他一切正常:

像这样创建两个队列:

private Queue<BluetoothGattDescriptor> descriptorWriteQueue = new LinkedList<BluetoothGattDescriptor>();
private Queue<BluetoothGattCharacteristic> characteristicReadQueue = new LinkedList<BluetoothGattCharacteristic>();

然后使用此方法在发现后立即编写所有描述符:

public void writeGattDescriptor(BluetoothGattDescriptor d){
    //put the descriptor into the write queue
    descriptorWriteQueue.add(d);
    //if there is only 1 item in the queue, then write it.  If more than 1, we handle asynchronously in the callback above
    if(descriptorWriteQueue.size() == 1){   
        mBluetoothGatt.writeDescriptor(d);      
    }
}

这个回调:

public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {         
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.d(TAG, "Callback: Wrote GATT Descriptor successfully.");           
        }           
        else{
            Log.d(TAG, "Callback: Error writing GATT Descriptor: "+ status);
        }
        descriptorWriteQueue.remove();  //pop the item that we just finishing writing
        //if there is more to write, do it!
        if(descriptorWriteQueue.size() > 0)
            mBluetoothGatt.writeDescriptor(descriptorWriteQueue.element());
        else if(readCharacteristicQueue.size() > 0)
            mBluetoothGatt.readCharacteristic(readQueue.element());
    };

读取特征的方法通常如下所示:

public void readCharacteristic(String characteristicName) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    BluetoothGattService s = mBluetoothGatt.getService(UUID.fromString(kYourServiceUUIDString));
    BluetoothGattCharacteristic c = s.getCharacteristic(UUID.fromString(characteristicName));
    //put the characteristic into the read queue        
    readCharacteristicQueue.add(c);
    //if there is only 1 item in the queue, then read it.  If more than 1, we handle asynchronously in the callback above
    //GIVE PRECEDENCE to descriptor writes.  They must all finish first.
    if((readCharacteristicQueue.size() == 1) && (descriptorWriteQueue.size() == 0))
        mBluetoothGatt.readCharacteristic(c);              
}

和我的阅读回调:

public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        readCharacteristicQueue.remove();
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);                                
        }
        else{
            Log.d(TAG, "onCharacteristicRead error: " + status);
        }

        if(readCharacteristicQueue.size() > 0)
            mBluetoothGatt.readCharacteristic(readCharacteristicQueue.element());
    }
于 2013-08-13T11:27:50.890 回答
11

当将值设置为描述符而不是 putdescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)时, put descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)。现在调用 onCharacteristicChanged 的​​回调。

于 2013-10-27T23:24:39.637 回答
7

我假设(您没有提供源代码)您没有按照Google 的要求实现它:

(1)

mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

接着

(2)

BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

我想 2 不见了。在那种情况下,我相信会触发低级通知,但它们永远不会被报告给应用层。

于 2016-07-12T12:43:38.907 回答
6

在早期版本的 Android 接收通知(已注册的指示)中遇到问题,之后总是出现奇怪的断开连接事件。事实证明,这是因为我们注册了五个特征的通知。

在 LogCat 中发现的错误是:

02-05 16:14:24.990    1271-1601/? E/bt-btif﹕ Max Notification Reached, registration failed.

在 4.4.2 之前,注册数量上限为 4!4.4.2 将此限制增加到 7。

通过减少早期版本中的注册数量,我们能够绕过这个限制。

于 2015-02-05T21:33:03.737 回答
4

好吧,如果他/她不是蓝牙后台程序员,这个 API 名称肯定会给应用开发者带来一些困惑。

从蓝牙核心规范的角度来看,引用 core spec 4.2 Vol 3, Part G section 3.3.3.3 “Client Characteristic Configuration”:

特征描述符值是一个位字段。当一个位被设置时,那个动作应该被启用,否则它不会被使用。

和第 4.10 节

可以使用客户端特征配置描述符来配置通知(参见第 3.3.3.3 节)。

这明确指出,如果客户端想要接收来自服务器的通知(或需要响应的指示),应将“通知”位写入 1(否则“指示”位也写入 1)。

但是,“setCharacteristicNotification”这个名字给我们的一个提示是,如果我们将此 API 的参数设置为 TURE,客户端就会收到通知;不幸的是,此 API 仅设置本地位以允许在远程通知到来的情况下将通知发送到应用程序。请参阅 Bluedroid 的代码:

    /*******************************************************************************
    **
    ** Function         BTA_GATTC_RegisterForNotifications
    **
    ** Description      This function is called to register for notification of a service.
    **
    ** Parameters       client_if - client interface.
    **                  bda - target GATT server.
    **                  p_char_id - pointer to GATT characteristic ID.
    **
    ** Returns          OK if registration succeed, otherwise failed.
    **
    *******************************************************************************/

    tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications (tBTA_GATTC_IF client_if,
                                                         BD_ADDR bda,
                                                         tBTA_GATTC_CHAR_ID *p_char_id)

{
    tBTA_GATTC_RCB      *p_clreg;
    tBTA_GATT_STATUS    status = BTA_GATT_ILLEGAL_PARAMETER;
    UINT8               i;

    if (!p_char_id)
    {
        APPL_TRACE_ERROR("deregistration failed, unknow char id");
        return status;
    }

    if ((p_clreg = bta_gattc_cl_get_regcb(client_if)) != NULL)
    {
        for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i ++)
        {
            if ( p_clreg->notif_reg[i].in_use &&
                 !memcmp(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN) &&
                  bta_gattc_charid_compare(&p_clreg->notif_reg[i].char_id, p_char_id))
            {
                APPL_TRACE_WARNING("notification already registered");
                status = BTA_GATT_OK;
                break;
            }
        }
        if (status != BTA_GATT_OK)
        {
            for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i ++)
            {
                if (!p_clreg->notif_reg[i].in_use)
                {
                    memset((void *)&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG));

                    p_clreg->notif_reg[i].in_use = TRUE;
                    memcpy(p_clreg->notif_reg[i].remote_bda, bda, BD_ADDR_LEN);

                    p_clreg->notif_reg[i].char_id.srvc_id.is_primary = p_char_id->srvc_id.is_primary;
                    bta_gattc_cpygattid(&p_clreg->notif_reg[i].char_id.srvc_id.id, &p_char_id->srvc_id.id);
                    bta_gattc_cpygattid(&p_clreg->notif_reg[i].char_id.char_id, &p_char_id->char_id);

                    status = BTA_GATT_OK;
                    break;
                }
            }
            if (i == BTA_GATTC_NOTIF_REG_MAX)
            {
                status = BTA_GATT_NO_RESOURCES;
                APPL_TRACE_ERROR("Max Notification Reached, registration failed.");
            }
        }
    }
    else
    {
        APPL_TRACE_ERROR("Client_if: %d Not Registered", client_if);
    }

    return status;
}'

所以重要的是描述符写入操作。

于 2016-07-19T05:58:39.893 回答
1

这是一种简单的方法,但如果您发现任何缺点,请告诉我。

步骤 1 声明布尔变量

private boolean char_1_subscribed = false;
private boolean char_2_subscribed = false;
private boolean char_3_subscribed = false;

第 2 步 订阅 onServicesDiscovered 回调中的第一个特征:

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if(!char_1_subscribed)
        subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_1)); char_1_subscribed = true;
}

第 3 步

在 onCharacteristicChanged 回调触发后订阅任何其他人

@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                    BluetoothGattCharacteristic characteristic) {
    if(UUID_CHAR_1.equals(characteristic.getUuid()))
    {
        if(!char_1_subscribed)
            subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_2)); char_2_subscribed = true;
    }
    if(UUID_CHAR_2.equals(characteristic.getUuid()))
    {
        if(!char_3_subscribed)
            subscribeToNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_CHAR_3)); char_3_subscribed = true;
    }
}
于 2015-07-13T19:22:03.140 回答
1

这个对我有用:

要通知主设备某些特性发生了变化,请在您的外设上调用此函数:

private BluetoothGattServer server;
//init....

//on BluetoothGattServerCallback...

//call this after change the characteristic
server.notifyCharacteristicChanged(device, characteristic, false);

在您的主设备中:发现服务后启用 setCharacteristicNotification:

@Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        services = mGatt.getServices();
        for(BluetoothGattService service : services){
            if( service.getUuid().equals(SERVICE_UUID)) {
                characteristicData = service.getCharacteristic(CHAR_UUID);
                for (BluetoothGattDescriptor descriptor : characteristicData.getDescriptors()) {
                    descriptor.setValue( BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                    mGatt.writeDescriptor(descriptor);
                }
                gatt.setCharacteristicNotification(characteristicData, true);
            }
        }
        if (dialog.isShowing()){
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    dialog.hide();
                }
            });
        }
   }

现在您可以检查您的特征值是否发生变化,例如 onCharacteristicRead 函数(这也适用于 onCharacteristicChanged 函数):

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        Log.i("onCharacteristicRead", characteristic.toString());
        byte[] value=characteristic.getValue();
        String v = new String(value);
        Log.i("onCharacteristicRead", "Value: " + v);
}
于 2016-12-18T11:28:52.420 回答
0

我还有另一个原因要补充,因为它让我一整天都发疯了:

在我的三星 Note 3 上,我没有收到更改值的通知,而相同的代码在我测试过的任何其他设备上都可以工作。

重新启动设备解决了所有问题。很明显,但是当你遇到问题时,你会忘记去想。

于 2015-05-07T07:04:27.960 回答
-1

我也遇到过 Android 上的 BLE 通知问题。但是有一个完整的演示,其中包括一个蓝牙包装器BluetoothAdapter。包装器被调用并随包含在应用程序加速器包中的名为BLEDemoBleWrapper的演示应用程序一起提供。在此处下载:https ://developer.bluetooth.org/Pages/Bluetooth-Android-Developers.aspx 。您需要在下载前使用右上角的电子邮件地址进行注册。该项目的许可证允许免费使用、代码修改和发布。

根据我的经验,Android 演示应用程序可以很好地处理 BLE 通知订阅。我还没有深入研究代码以了解包装器实际上是如何包装的。

Play Store 中有一个 Android 应用程序,它是对应用程序加速器演示的自定义。由于用户界面看起来几乎相同,我想它也使用BleWrapper. 在此处下载应用程序:https: //play.google.com/store/apps/details?id=com.macdom.ble.blescanner

于 2015-08-05T10:04:26.953 回答