BLE GATT onCharacteristicChanged在订阅通知后未调用

时间:2018-04-06 10:12:02

标签: android bluetooth-lowenergy android-bluetooth

订阅后通知立即写入命令不起作用。我必须重新启动服务器设备并自动连接到现有的ble实例才能获得结果。

通知启用代码:

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

    System.out.println("descriptor length----" + characteristic.getDescriptors().size());

    // This is specific to Heart Rate Measurement.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));

        System.out.println("descriptor--" + Arrays.toString(descriptor.getValue()));
        System.out.println("characteristic value--" + Arrays.toString(descriptor.getCharacteristic().getValue()));
             descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        return mBluetoothGatt.writeDescriptor(descriptor);
    }
    return false;
}

,这是我的写命令代码:

 public void writeCustomCharacteristic(String value) {


    this.value = "";
    this.command = value;
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("65333333-a115-11e2-9e9a-0800200ca100"));
    if (mCustomService == null) {
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("65333333-a115-11e2-9e9a-0800200ca101"));
    mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

        mWriteCharacteristic.setValue(value.getBytes());
        if (!mBluetoothGatt.writeCharacteristic(mWriteCharacteristic)) {
            Log.w(TAG, "Failed to write characteristic");
        }

    System.out.println("BluetoothLeService.writeCustomCharacteristic------->" + value);

}

1 个答案:

答案 0 :(得分:0)

在写入任何特征之前,延迟几秒钟。 Bcz需要时间来执行。

 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mBluetoothGatt.writeDescriptor(RTS_CCCD); //for descriptor
  //  or
    mBluetoothGatt.readCharacteristic(brspInfo); //for read
//or
    mBluetoothGatt.writeCharacteristic(brspInfo); //for write
                            }
                        }, 500);

Here你得到更多的解释