setCharacteristicNotification 不会触发 onCharacteristicChanged

setCharacteristicNotification doesn't trigger onCharacteristicChanged

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

获取我的特征的方法:

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 开始被调用(我可以看到 "characteristic changed" 在 logcat).

我解决了这个问题。我不得不 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);
}