Android Studio开发BLE:如何解析BluetoothGattService的有效信息
解决BLE服务打印无意义信息的问题
哈哈,这个我刚接触BLE开发的时候也踩过一模一样的坑!你看到的android.bluetooth.BluetoothGattService@41b6dd18其实是Java对象默认的toString()输出——就是类名加上对象的内存哈希码,对我们理解BLE服务完全没用。要拿到有用的信息,得手动提取BluetoothGattService里的核心属性:
核心信息提取方法
每个BLE服务和特征都有几个关键字段是我们需要的,直接调用对应的API就能获取:
1. 服务的UUID
UUID是BLE服务/特征的唯一标识,分标准UUID(由蓝牙联盟定义,比如通用访问服务、电池服务)和厂商自定义UUID(外设厂商自己定义的功能服务)。调用service.getUuid().toString()就能拿到完整的UUID字符串。
2. 服务的类型
BLE服务分主服务和从属服务,调用service.getType()可以获取,再转成易读的字符串就行。
3. 服务下的特征列表
每个服务会包含多个特征,调用service.getCharacteristics()拿到特征列表后,再对每个特征提取UUID、属性(可读/可写/通知/指示等),这些属性决定了你能对这个特征做什么操作。
代码示例(直接在onServicesDiscovered中使用)
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 获取所有服务 List<BluetoothGattService> services = gatt.getServices(); for (BluetoothGattService service : services) { Log.d("BLE_DEBUG", "=== 发现新服务 ==="); // 打印服务UUID Log.d("BLE_DEBUG", "服务UUID: " + service.getUuid().toString()); // 打印服务类型 Log.d("BLE_DEBUG", "服务类型: " + getServiceTypeDesc(service.getType())); // 遍历服务下的所有特征 List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); for (BluetoothGattCharacteristic characteristic : characteristics) { Log.d("BLE_DEBUG", "--- 特征信息 ---"); Log.d("BLE_DEBUG", "特征UUID: " + characteristic.getUuid().toString()); Log.d("BLE_DEBUG", "特征属性: " + getCharacteristicPropDesc(characteristic.getProperties())); } } } else { Log.e("BLE_DEBUG", "服务发现失败,状态码: " + status); } } // 辅助方法:把服务类型转成易读描述 private String getServiceTypeDesc(int type) { switch (type) { case BluetoothGattService.SERVICE_TYPE_PRIMARY: return "主服务"; case BluetoothGattService.SERVICE_TYPE_SECONDARY: return "从属服务"; default: return "未知类型"; } } // 辅助方法:把特征属性转成易读描述 private String getCharacteristicPropDesc(int properties) { StringBuilder desc = new StringBuilder(); if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) != 0) { desc.append("可读 "); } if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) { desc.append("可写 "); } if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0) { desc.append("无响应写入 "); } if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) { desc.append("通知 "); } if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) { desc.append("指示 "); } return desc.length() > 0 ? desc.toString().trim() : "无可用属性"; }
额外说明
- 如果你拿到的是标准UUID(比如以
0000xxxx-0000-1000-8000-00805f9b34fb结尾的),可以直接对应蓝牙联盟定义的标准功能; - 如果是自定义UUID,就得找外设厂商要对应的协议文档,才能知道这个服务/特征的具体用途(比如控制LED、传输传感器数据等)。
内容的提问来源于stack exchange,提问作者MXG123
相关产品推荐
相关产品推荐

