2024年3月7日
uniapp使用低功耗蓝牙uni.onBluetoothDeviceFound实时判断uni.getBluetoothDevices中的蓝牙设备是否可用
官方给出的uni-app官网 (dcloud.net.cn)
其中注意
- 该接口获取到的设备列表为蓝牙模块生效期间所有搜索到的蓝牙设备,若在蓝牙模块使用流程结束后未及时调用
uni.closeBluetoothAdapter
释放资源,会存在调用该接口会返回之前的蓝牙使用流程中搜索到的蓝牙设备,可能设备已经不在用户身边,无法连接。
会存在这样一个问题,uni.getBluetoothDevices只会增加不会减少,如果该蓝牙设备断电或者不在身边,蓝牙列表无法实时刷新显示,会给用户造成困扰,可以将uni.startBluetoothDevicesDiscovery的allowDuplicatesKey传参改为true,uni.onBluetoothDeviceFound就会实时获取周围的蓝牙设备的广播信号,可以将获取到的设备name和获取道德当前时间进行缓存记录,蓝牙列表页可以进行缓存中的时间超时判断,超过一定时间没有监听到广播从列表中剔除,从而实现蓝牙设备是否可用实时显示,代码如下:
loadBlue() { let that = this uni.openBluetoothAdapter({ success(res) { uni.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, success(res) { uni.onBluetoothDeviceFound(function (devices) { uni.setStorageSync('tmsi'+devices.devices[0].name,new Date()); uni.getBluetoothDevices({ success(res) { if (res.devices.length > 0){ uni.setStorageSync('bleList',res.devices); } } }) }) } }) }, }) },