android - 具有自动连接 true 的 Android connectGatt 从未调用过`onConnectionStateChange`
问题描述
我的代码示例很简单:
connectButton.setOnClickListener {
(getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.getRemoteDevice(
"44:73:D6:0A:EA:79"
)?.let {
Log.i(TAG, "trying to connect ${it.type}")
val gatt = it.connectGatt(this, true, object : BluetoothGattCallback() {
override fun onConnectionStateChange(
gatt: BluetoothGatt?,
status: Int,
newState: Int
) {
Log.i(TAG, "connection status: $status, newState: $newState")
}
}, TRANSPORT_AUTO)
Log.i(TAG, "gatt is $gatt")
}
使用 autoConnect=true,里面的日志onConnectionStateChange
永远不会打印。
I/BLE: trying to connect 2
D/BluetoothGatt: connect() - device: 44:73:D6:0A:EA:79, auto: true
registerApp()
registerApp() - UUID=6376adc0-c38c-4088-8da7-2175a640cec2
I/BLE: gatt is android.bluetooth.BluetoothGatt@415f1c6
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=5
如果为 false,它会再打印三行
I/BLE: connection status: 0, newState: 2
D/BluetoothGatt: onConnectionUpdated() - Device=44:73:D6:0A:EA:79 interval=6 latency=0 timeout=500 status=0
D/BluetoothGatt: onConnectionUpdated() - Device=44:73:D6:0A:EA:79 interval=36 latency=0 timeout=500 status=0
在安装了 android 10 的华为 Mate20 上测试。
编辑:外围设备由另一个 android/iOS 设备模拟,当连接到 Bose 耳机时,这个片段似乎很好,我能做些什么来使模拟设备也能正常工作吗?
解决方案
Android API 缺少“地址类型”参数,这是一个设计错误。您的外围设备使用随机可解析地址进行广告宣传,在这种情况下,使用蓝牙地址直接连接是个坏主意。相反,您应该先执行 BLE 扫描,然后连接到找到的设备。这样,Android 从广告数据中“学习”地址类型,然后可以使用正确的地址类型进行连接。
推荐阅读
- php - 在 codeigniter 中与 union 进行内部连接
- c# - 在我的 UWP 应用程序中打开来自 Windows 的所有 http 链接
- flutter - 如何让 Flutter 应用在所有设备中打开。因为找不到 libflutter.so 而崩溃。我该如何解决?
- php - Chartjs中的范围分组数据和标签
- c# - 如何禁用 2 个同名组件
- python - TypeError:“zip”对象在 Python 中不可调用
- machine-learning - 我们可以用旧数据保存 lda 模型并将经过训练的模型用于新数据吗?
- r - R中的复杂循环或函数
- reactjs - 是否可以将 React 拆分窗格与两个以上的窗格一起使用?
- c - 将 UART 与 RPi Pico C sdk 一起使用时遇到问题