首页 > 解决方案 > 具有自动连接 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 耳机时,这个片段似乎很好,我能做些什么来使模拟设备也能正常工作吗?

标签: androidbluetooth-lowenergy

解决方案


Android API 缺少“地址类型”参数,这是一个设计错误。您的外围设备使用随机可解析地址进行广告宣传,在这种情况下,使用蓝牙地址直接连接是个坏主意。相反,您应该先执行 BLE 扫描,然后连接到找到的设备。这样,Android 从广告数据中“学习”地址类型,然后可以使用正确的地址类型进行连接。


推荐阅读