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

Android Java开发:如何将BLE GAP特征值转为可读字符串?

解决BLE GAP特征值转可读字符串问题

要把GAP服务(UUID 0x180A)下的特征值从字节数组转成可读字符串,核心是通过蓝牙回调获取读取结果,再按对应编码转换——因为BLE特征读取是异步操作,调用readCharacteristic后不会立刻返回数据,必须在BluetoothGattCallback的回调方法中处理结果。

步骤1:实现onCharacteristicRead回调

在你的BluetoothGattCallback子类中重写onCharacteristicRead方法,这里是获取特征值并转换的关键位置:

import java.nio.charset.StandardCharsets;
import java.util.UUID;

// 假设这是你的BluetoothGattCallback实现类
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);
        // 检查读取是否成功
        if (status == BluetoothGatt.GATT_SUCCESS) {
            UUID charUuid = characteristic.getUuid();
            byte[] rawValue = characteristic.getValue();
            
            if (rawValue == null) {
                Log.d("BLE", "特征值为空");
                return;
            }

            // 处理制造商名称特征(UUID: 0x2A29)
            if (charUuid.equals(UUID.fromString("00002a29-0000-1000-8000-00805f9b34fb"))) {
                String manufacturerName = new String(rawValue, StandardCharsets.UTF_8);
                // 这里可以将字符串发送到服务器或显示
                Log.d("BLE", "制造商名称: " + manufacturerName);
            }
            // 处理型号名称特征(UUID: 0x2A24)
            else if (charUuid.equals(UUID.fromString("00002a24-0000-1000-8000-00805f9b34fb"))) {
                String modelName = new String(rawValue, StandardCharsets.UTF_8);
                Log.d("BLE", "型号名称: " + modelName);
            }
            // 可扩展处理其他GAP特征,比如序列号(0x2A25)、硬件修订(0x2A27)等
        } else {
            Log.e("BLE", "读取特征失败,状态码: " + status);
        }
    }

    // 其他回调方法(比如onConnectionStateChange、onServicesDiscovered)保持你的现有实现
};

步骤2:确保初始化Gatt时绑定回调

在连接BLE设备时,必须传入上述gattCallback实例:

// 替换你现有连接设备的代码
mBluetoothGatt = bluetoothDevice.connectGatt(this, false, gattCallback);

关键说明

  • 编码选择:GAP服务下的制造商、型号等特征值默认使用UTF-8编码,所以用StandardCharsets.UTF_8(API 26及以上);如果需要兼容更低版本,可替换为"UTF-8"字符串:new String(rawValue, "UTF-8")。
  • 异步读取逻辑:你调用readCharacteristic后,系统会在后台完成读取,结果通过onCharacteristicRead返回,这也是你之前只看到十六进制值却无法转换的核心原因——没有在回调里处理真正的字节数据。
  • 特征UUID对应:GAP服务下常用特征的UUID:
    • 制造商名称:00002a29-0000-1000-8000-00805f9b34fb
    • 型号名称:00002a24-0000-1000-8000-00805f9b34fb
    • 序列号:00002a25-0000-1000-8000-00805f9b34fb

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:00:55