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

使用Flutter Blue Plus连接HC-06蓝牙模块失败求助

解决Flutter连接HC-06蓝牙模块的问题

核心问题分析

HC-06是基于经典蓝牙(BR/EDR)的SPP串口模块,而FlutterBluePlus主要针对BLE(低功耗蓝牙)开发,对经典蓝牙的SPP协议支持有限,这是连接失败的核心原因之一。另外,Android 12及以上版本的蓝牙权限要求更新,现有权限不足以完成连接操作。


解决方案

1. 补充Android权限(适配Android 12+)

在AndroidManifest.xml中添加针对高版本系统的蓝牙权限,确保权限覆盖完整:

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />

保留原有已添加的权限,适配不同Android版本的需求。

2. 更换为经典蓝牙专用库

推荐使用flutter_bluetooth_serial库,它专门针对经典蓝牙SPP协议开发,完美适配HC-06这类串口蓝牙模块。

示例代码片段:

import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

// 连接已配对的HC-06设备
void connectToHC06(BluetoothDevice device) async {
  try {
    BluetoothConnection connection = await BluetoothConnection.toAddress(device.address);
    print('连接成功');
    
    // 监听设备返回的数据
    connection.input?.listen((data) {
      print('收到数据: ${String.fromCharCodes(data)}');
    }).onDone(() {
      print('连接断开');
    });
  } catch (error) {
    print('连接失败: $error');
  }
}

3. 若坚持使用FlutterBluePlus的处理方式

如果继续使用FlutterBluePlus,需要手动发现SPP服务并完成连接:

onTap: () async {
  print("Connecting...");
  try {
    await device.connect(autoConnect: false);
    // 发现设备服务
    List<BluetoothService> services = await device.discoverServices();
    // 查找SPP服务的固定UUID:00001101-0000-1000-8000-00805F9B34FB
    BluetoothService? sppService = services.firstWhere(
      (s) => s.uuid.toString() == "00001101-0000-1000-8000-00805F9B34FB",
      orElse: () => BluetoothService(uuid: Guid(""), characteristics: []),
    );
    if (sppService.uuid.toString().isNotEmpty) {
      print("找到SPP服务,连接成功");
    } else {
      print("未找到SPP服务");
      await device.disconnect();
    }
  } catch (error) {
    print("连接错误: $error");
  }
},

4. 清理蓝牙缓存

日志中出现clearGattCache提示,说明Gatt缓存可能干扰连接:

  • 重启手机和HC-06模块
  • 在手机蓝牙设置中忽略HC-06设备,重新配对后再尝试连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:30:23