我们正在编写一个 ble 应用程序,希望与我们想要连接的外设建立持久连接。出于同样的目的,每当我们失去现有连接时,我们都希望与外围设备重新连接。因此,我们作为中心的 Android 应用程序只是尝试通过调用 bluetoothdevice.connectgatt 并将 autoconnect 设置为 true 来创建新的 bluetoothgatt 对象来重新连接。
但每当我们尝试这样做时,我们的重新连接就会失败
12-02 21:47:11.865: D/BluetoothGatt(31963): onClientConnectionState() - status=133 clientIf=6 device=******** callback.
因为我们的连接请求被视为 Nexus 5 Lollipop 上的直接连接请求
这是日志
12-03 11:46:12.804: D/BluetoothGatt(6902): connect() - device: 58:EB:14:3D:2A:38, auto: true
12-03 11:46:12.804: D/BluetoothGatt(6902): registerApp()
12-03 11:46:12.804: D/BluetoothGatt(6902): registerApp() - UUID=b8f9298b-4a95-41be-80d6-22d82c498c5c
12-03 11:46:12.807: D/BtGatt.GattService(31817): registerClient() - UUID=b8f9298b-4a95-41be-80d6-22d82c498c5c
12-03 11:46:12.808: D/BtGatt.GattService(31817): onClientRegistered() - UUID=b8f9298b-4a95-41be-80d6-22d82c498c5c, clientIf=6
12-03 11:46:12.808: D/BluetoothGatt(6902): onClientRegistered() - status=0 clientIf=6
12-03 11:46:12.808: D/BtGatt.GattService(31817): clientConnect() - address=58:EB:14:3D:2A:38, isDirect=true
12-03 11:46:12.809: D/BtGatt.btif(31817): btif_get_device_type: Device [58:eb:14:3d:2a:38] type 2, addr. type 0
12-03 11:46:12.811: D/BLEManager(6902): Trying to create a new connection.
该问题已在 2016 年 5 月的 master android 分支中得到修复。关于它是否最终出现在 Nougat 中的报告不一,可能与设备有关,但它肯定仍然是 Marshmallow 中的一个错误。
由于 IBluetoothManager 和 IBluetoothGatt 类在用户代码中不可用,因此解决方法所需的反射代码很快就会变得复杂。
幸运的是,有人已经编写了一个非常小、清晰的库,它为我们完成了这个确切的例程。
https://github.com/Polidea/RxAndroidBle/blob/master/rxandroidble/src/main/java/com/polidea/rxandroidble/internal/util/BleConnectionCompat.java
使用此类,只需调用:
mBluetoothGatt = (new BleConnectionCompat(context)).connectGatt(device, autoConnect, callback)
代替
mBluetoothGatt = device.connectGatt(context, autoConnect, callback);
它对我来说效果很好。我对此没有任何功劳,这完全是uKL
另请注意,它遵循 Apache License 2.0 版权所有 2016 Polidea Sp。动物园
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)