setCharacteristicNotification不会触发onCharacteristicChanged

时间:2016-09-14 11:07:09

标签: android bluetooth-lowenergy gatt

我尝试阅读外围设备的特性但是,尽管设置了onCharacteristicChanged,但setCharacteristicNotification从未被调用过。

获得我特色的方法:

private void getCharacteristic(List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;

    for (BluetoothGattService gattService : gattServices) {
        if (gattService.getUuid().toString().equals("000018f0-0000-1000-8000-00805f9b34fb")) {
            for (BluetoothGattCharacteristic gattCharacteristic : gattService.getCharacteristics()) {
                if (gattCharacteristic.getUuid().toString().equals("00002af0-0000-1000-8000-00805f9b34fb")) {
                    mBluetoothLeService.setCharacteristicNotification(gattService.getCharacteristic(gattCharacteristic.getUuid()), true);
                }
            }
        }
    }
}

设置通知:

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
永远不会触发的

onCharacteristicChanged方法:

@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        Log.d(TAG, "characteristic changed");
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

相同的代码适用于不同的外围设备。

我还从Google Play商店下载了nRF Connect应用程序,该应用程序显示了特征,当我在nRF Connect中启用通知时,我的应用程序中的onCharacteristicChanged开始被调用(我可以在logcat中看到“特性已更改”)。 / p>

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我必须writeDescriptor到我的BluetoothGatt,所以我的setCharacteristicNotificiation看起来像这样:

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
        UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
}