uniapp uni.onbluetoothdevicefound多次触发如何解决
在使用uniapp的uni.onbluetoothdevicefound监听蓝牙设备时,发现回调函数会多次触发,导致同一设备被重复处理。请问如何避免这种重复触发的情况?是否需要在某些时机手动取消监听?期待有经验的开发者分享解决方案。
2 回复
在uni.onBluetoothDeviceFound
回调中,使用uni.offBluetoothDeviceFound
停止监听即可。建议在获取到设备后立即关闭监听,避免重复触发。
在 UniApp 中,uni.onBluetoothDeviceFound
方法用于监听蓝牙设备发现事件,但可能会因设备广播或扫描机制导致多次触发同一设备。以下是解决方法:
1. 使用防抖(Debounce)
通过防抖函数延迟处理,避免频繁触发。示例代码:
let timer = null;
uni.onBluetoothDeviceFound((devices) => {
clearTimeout(timer);
timer = setTimeout(() => {
// 处理设备逻辑,例如去重
console.log('发现设备:', devices);
}, 500); // 延迟500毫秒
});
2. 设备去重
基于设备ID(如 deviceId
)过滤重复设备。示例代码:
let foundDevices = {}; // 存储已发现设备
uni.onBluetoothDeviceFound((result) => {
const device = result.devices[0];
if (!foundDevices[device.deviceId]) {
foundDevices[device.deviceId] = device; // 记录新设备
console.log('新设备:', device);
}
});
3. 停止扫描后移除监听
在找到目标设备后,停止扫描并移除监听:
uni.stopBluetoothDevicesDiscovery(); // 停止扫描
uni.offBluetoothDeviceFound(); // 移除监听
4. 优化扫描参数
调整扫描间隔或使用 uni.startBluetoothDevicesDiscovery
的 interval
参数(部分平台支持)减少频率。
总结
推荐结合 防抖 和 设备去重 来处理多次触发问题,确保应用性能。根据需求及时停止扫描和移除监听,避免资源浪费。