首页 > 解决方案 > 颤动蓝色实例连接在Android中自动断开

问题描述

我已经用 BLE 完成了一个用 Flutter 编写的应用程序,并且在 iOS 中运行良好。

但是当我在 Android 中运行相同的应用程序时,它无法正常工作。所以我检查了日志,发现应用程序没有连接到稳定的蓝牙设备,一旦连接,它就会断开连接。

所以我写了一个代码来监听蓝牙连接的状态变化,并在状态变为断开连接时重新连接,并在日志中发现它像循环一样继续连接和断开连接。

请注意,这在 iOS 中也能完美运行。

Launching lib/main.dart on TRT L21A in debug mode...
Built build/app/outputs/apk/debug/app-debug.apk.
I/flutter (10374): getHOME, statusCode = 200
I/flutter (10374): Body Batch: {status: success, target_steps: 10000, today_steps: 0, calorie_target: 2000, today_calories: 0, totaldistance: 0, team_leader: no}
I/hwaps   (10374): JNI_OnLoad
I/BluetoothAdapter(10374): getBluetoothLeScanner
I/flutter (10374):
I/BluetoothAdapter(10374): getBluetoothLeScanner
I/BluetoothGatt(10374): connect is called
I/BluetoothGatt(10374): connect is called
I/art     (10374): Do partial code cache collection, code=30KB, data=30KB
I/art     (10374): After code cache collection, code=30KB, data=30KB
I/art     (10374): Increasing code cache capacity to 128KB
I/flutter (10374): State is BluetoothDeviceState.disconnected
I/BluetoothGatt(10374): connect is called
I/flutter (10374): State is BluetoothDeviceState.disconnected
I/BluetoothGatt(10374): connect is called
I/flutter (10374): State is BluetoothDeviceState.disconnected
I/BluetoothGatt(10374): connect is called
I/flutter (10374): State is BluetoothDeviceState.connected
I/flutter (10374): State is BluetoothDeviceState.connected
I/flutter (10374): State is BluetoothDeviceState.connected
I/flutter (10374): State is BluetoothDeviceState.connected

标签: flutterdartbluetooth-lowenergy

解决方案


有一个与您的问题相关的开放 GitHub问题。有些人有一个快速修复,包括这个评论

我只是保留了一个标志 hasConnected,我将其设置为已连接,然后我只关心 hasConnected 为真后的断开连接。可能无法解决所有问题,但应该带您通过第一个。此外,当出现错误时,我发现了一个“断开连接”,然后是第二个“断开连接”,因此如果它为我解决了断开连接,则只需忽略第一条消息。


推荐阅读