背景:
我有一个BLE外设有两种模式:“应用程序”和“引导程序”.在这两种模式下,设备都使用相同的MAC地址进行通告.
要从一种模式切换到另一种模式,BLE外设必须自行重启.在这样做时,它必须断开任何活动的BLE连接.
BLE外设仅在Bootloader模式下保持约5秒钟.如果没有人在该窗口内连接它,它将切换到应用程序模式.
问题:
Android需要很长时间才能重新连接到BLE设备,足够长,以至于我错过了5秒窗口.原始代码有几层到BluetoothGATT和BluetoothAdapter层,但调用顺序归结为:
BluetoothGattCharacteristic c = mCharacteristics.get(POWER_STATE_UUID);
c.setValue(SHUTDOWN_VALUE);
mBluetoothGatt.writeCharacteristic(c);
// Signalled by BluetoothGattCallback.onCharacteristicWrite
bleWriteCondition.await();
mBluetoothGatt.disconnect();
// Wait for the underlying layer to confirm we're disconnected
while( mConnectionState != BluetoothProfile.STATE_DISCONNECTED ) {
// Signalled by BluetoothGattCallback.onConnectionStateChange
bleStateCondition.await();
}
mBluetoothGatt.connect();
while (mConnectionState != BluetoothProfile.STATE

在Android设备上,当尝试重新连接BLE外设时,尤其是面对短暂可用窗口时,常规的连接方法可能会导致连接速度过慢。解决方案在于使用低延迟扫描模式和直接连接请求。在发现设备后立即发起直接连接,通过`setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)`设置扫描模式,并在`connectGatt`方法中传入`false`参数,以加速连接过程。这样可以提高在有限时间内成功连接到BLE设备的概率。
最低0.47元/天 解锁文章
408

被折叠的 条评论
为什么被折叠?



