Android BLE - 重新连接后读/写命令失败

问题描述

我正在处理一个 Android BLE 项目,我注意到连接在随机情况下意外断开。从 SO 上已经发布的大量连接相关问题来看,这在 Android BLE 堆栈上显然是正常的。回到这个问题,当连接意外断开时,我重新连接设备。但是,在建立新连接后,读/写操作不断失败。这是我用来重新连接的代码。 请注意,我还尝试在 bluetoothGatt.disconnect() 方法中注释 bluetoothGatt.close()reconnect,但效果不佳。

    private val myGattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt?,status: Int,newState: Int) {
            super.onConnectionStateChange(gatt,status,newState)

            gatt ?: return

            when (status) {
                BluetoothGatt.GATT_SUCCESS -> {

                    when (newState) {

                        BluetoothProfile.STATE_CONNECTED -> {                            
                            gatt.discoverServices()
                        }

                        BluetoothProfile.STATE_disCONNECTED -> {
                            gatt.close()
                        }
                    }
                }
                else -> {
                    // if the connection is lost unexpectedly
                    reconnect(gatt)
                }
            }
        }
    }

    private fun reconnect(bluetoothGatt: BluetoothGatt) {
        bluetoothGatt.disconnect()
        bluetoothGatt.close()

        bluetoothGatt.device.connectGatt(MyApp.context,false,myGattCallback)
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)