使用flutter_bluetooth_Serial连接蓝牙时触发PlatformException连接错误
蓝牙连接失败(read failed)排查方案
问题日志与异常
D/FlutterBluePlugin(29052): Starting discovery I/BluetoothAdapter(29052): startDiscovery D/FlutterBluePlugin(29052): Discovered 50:9A:3B:BF:BC:AA D/FlutterBluePlugin(29052): Discovered 78:02:B7:DA:EE:47 I/ViewRootImpl@8cce0a6[MainActivity](29052): ViewPostIme pointer 0 I/ViewRootImpl@8cce0a6[MainActivity](29052): ViewPostIme pointer 1 D/FlutterBluePlugin(29052): Connecting to 78:02:B7:DA:EE:47 (id: 1) I/BluetoothAdapter(29052): cancelDiscovery I/BluetoothSocket(29052): connect() for device XX:XX:XX:XX:EE:47 called by pid: 29052 D/FlutterBluePlugin(29052): Discovery finished I/BluetoothAdapter(29052): cancelDiscovery D/FlutterBluePlugin(29052): Canceling discovery (stream closed) I/BluetoothAdapter(29052): cancelDiscovery I/flutter (29052): 无法连接,发生异常:PlatformException(connect_error, read failed, socket might closed or timeout, read ret: -1, java.io.IOException: read failed, socket might closed or timeout, read ret: -1 I/flutter (29052): at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:1054) I/flutter (29052): at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:1068) I/flutter (29052): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:583) I/flutter (29052): at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:57) I/flutter (29052): at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:64) I/flutter (29052): at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler.lambda$onMethodCall$4$io-github-edufolly-flutterbluetoothserial-FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler(FlutterBluetoothSerialPlugin.java:1007) I/flutter (29052): at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCal
排查步骤
确认设备配对状态
先在系统蓝牙设置中手动配对目标设备(78:02:B7:DA:EE:47),输入正确配对码(常见0000、1234),确保配对成功后再通过代码发起连接。未配对直接连接大概率触发此类异常。验证蓝牙UUID正确性
经典蓝牙串口设备(SPP协议)通用UUID为00001101-0000-1000-8000-00805F9B34FB,如果代码中使用了自定义UUID,替换为该标准UUID重试。延长连接超时时间
部分设备响应较慢,默认超时时间不足。尝试在连接时设置5000ms以上的超时,避免因设备响应延迟导致的读取失败。断开其他设备连接
目标蓝牙设备同一时间仅支持一个串口连接,检查是否有其他设备(如电脑、另一部手机)已与该设备建立连接,断开后再重试。检查权限配置
确保AndroidManifest.xml中添加了完整的蓝牙权限:<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Android 12及以上需添加 --> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />同时在运行时动态申请这些权限,尤其是位置权限(Android 6.0+强制要求),缺失权限会导致蓝牙连接异常。
测试硬件兼容性
更换一台Android设备尝试连接,排除当前设备蓝牙模块的硬件兼容性问题。部分老旧设备的蓝牙模块对特定设备支持不佳。确认目标设备状态
检查目标设备是否处于可连接状态:串口服务已开启、未进入休眠模式、电量充足。部分设备闲置后会自动关闭蓝牙连接功能,需重新激活。
内容的提问来源于stack exchange,提问作者senthil raja
相关产品推荐
相关产品推荐

