首页 > 解决方案 > 如何检测 Android 蓝牙 connectGatt() 自动连接完成

问题描述

(*** 编辑 #2:尝试连接多个设备***)

我正在使用自动连接设置为 true 的 BluetoothDevice.connectGatt() 来连接到多个设备:

bluetoothDevice1.connectGatt(context, true, BLGattCallback(context), BluetoothDevice.TRANSPORT_LE)
bluetoothDevice2.connectGatt(context, true, BLGattCallback(context), BluetoothDevice.TRANSPORT_LE)

(*** Edit #1 ***) 我在 BluetoothGattCallback() 中使用 onConnectionStateChange():

internal class BLGattCallback(val context: BTLeashService) : BluetoothGattCallback()        // Todo: Convert to LiveData
{
    override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int)
    {
        super.onConnectionStateChange(gatt, status, newState)

        val connectionStateChange = BLBluetoothManager.ConnectionStateChange(gatt, status, newState)
        BLBluetoothManager.connectionStateChange.postValue(connectionStateChange)
    }

(结束编辑#1)

使用这种方法,我必须在执行下一个 connectGat() 之前使用延迟,否则前一个会中止。为什么是这样?我认为它不应该等待,只要它连接就回电......

当第一个 connectGatt 完成时是否有回调让您知道,这样我就不需要临时延迟?

*** 编辑 #3 ***

“第一个 connectGatt 完成”并不是说建立了连接,只是我现在可以执行下一个命令而不会中止上一个命令。

(结束编辑#3)

标签: androidbluetooth-lowenergyandroid-bluetooth

解决方案


推荐阅读