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

如何解决onCharacteristicChanged中messageBytes数组值显示混乱及取值问题?

解决BluetoothLeService中onCharacteristicChanged数组元素日志混乱问题

从你给出的Logcat日志来看,问题出在直接打印数组对象上——Java默认会输出数组的类型标识(比如日志里的[J就是long类型数组的标记)和对象的哈希信息,而不是我们想看的实际元素值。下面给你两个简单有效的方案,帮你准确获取并打印数组的单个元素:

方案一:遍历数组逐个打印元素

直接通过循环遍历数组,把每个元素单独输出,这样日志会非常清晰,还能看到每个元素的索引:

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    // 获取你需要的messageBytes数组
    byte[] messageBytes = characteristic.getValue();
    
    Log.i("BluetoothLeService", "onCharacteristicChanged - 数组元素详情:");
    // 循环遍历每个元素
    for (int index = 0; index < messageBytes.length; index++) {
        Log.i("BluetoothLeService", String.format("元素[%d]: %d", index, messageBytes[index]));
    }
    
    // 如果你的数组是其他类型(比如double/long),只需要调整类型即可
    // 比如处理double数组:
    // double[] doubleArray = ...;
    // for (int i = 0; i < doubleArray.length; i++) {
    //     Log.i("BluetoothLeService", String.format("元素[%d]: %.2f", i, doubleArray[i]));
    // }
}

方案二:用Arrays工具类格式化输出数组

如果你想先快速看到整个数组的整齐格式,再单独获取某个元素,可以用Java自带的Arrays工具类,它能帮你把数组转换成可读的字符串:

import java.util.Arrays;

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    byte[] messageBytes = characteristic.getValue();
    
    // 打印整个格式化后的数组
    Log.i("BluetoothLeService", "onCharacteristicChanged - 完整数组: " + Arrays.toString(messageBytes));
    
    // 直接通过索引获取单个元素(记得先判断数组长度,避免数组越界)
    if (messageBytes.length > 0) {
        byte firstElement = messageBytes[0];
        Log.i("BluetoothLeService", "第一个元素值: " + firstElement);
        
        // 比如获取第三个元素(索引从0开始)
        if (messageBytes.length > 2) {
            byte thirdElement = messageBytes[2];
            Log.i("BluetoothLeService", "第三个元素值: " + thirdElement);
        }
    }
}

额外说明

你日志里出现了2.86这样的小数,说明这个数组可能不是单纯的byte数组,而是经过解析后的数值数组(比如double)。如果是这种情况,记得先把byte数组转换成对应类型的数组,再用上面的方法打印元素——比如用ByteBuffer来处理字节序转换,确保数值解析准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:28:42