You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android API 33中BLE特征getValue已弃用,如何正确获取特征值?

Android API 33 中获取BLE特征值的正确方式

在API Level 33中,BluetoothGattCharacteristic.getValue()被弃用后,官方推荐的BluetoothGatt.readCharacteristic()是异步操作——它仅负责发起读取请求(返回布尔值表示请求是否成功提交),无法直接返回特征值,必须通过回调机制获取结果,具体操作步骤如下:

  1. 发起读取请求
    调用BluetoothGatt实例的readCharacteristic()方法传入目标特征,返回true则代表请求已成功发送:
BluetoothGattCharacteristic targetChar = ...; // 你的目标特征对象
boolean requestSuccess = bluetoothGatt.readCharacteristic(targetChar);
if (!requestSuccess) {
    // 处理请求发送失败的逻辑
}
  1. 通过回调接收读取结果
    实现BluetoothGattCallback并重写onCharacteristicRead()方法,系统会在读取操作完成后回调该方法,在这里获取并处理特征值:
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        // 根据特征值的数据类型选择对应方法获取
        // 示例1:获取字节数组(替代原getValue())
        byte[] valueBytes = characteristic.getByteArrayValue(0);
        // 示例2:获取字符串值
        String valueStr = characteristic.getStringValue(0);
        // 示例3:获取整数值(FORMAT_UINT8为数据格式,0为偏移量)
        int valueInt = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        
        // 这里添加对特征值的业务处理逻辑
    } else {
        // 读取失败,根据status码处理错误
    }
}

注意事项

  • 确保目标特征具备PROPERTY_READ权限,否则读取请求会直接失败。
  • 不同特征值对应不同的数据格式(如FORMAT_UINT8、FORMAT_UINT16等),需根据BLE设备的特征定义选择匹配的格式。
  • 异步操作无法同步返回结果,所有对特征值的处理必须在onCharacteristicRead回调中完成。

内容的提问来源于stack exchange,提问作者JScoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:34:59