1.首先判断蓝牙是否打开
// 一 初始化蓝牙模块 openBluetoothAdapter() { let _this = this; wx.openBluetoothAdapter({ // 成功回调函数 success(res) { // console.log(res) // 搜索提示 wx.showLoading({ title: '蓝牙搜索中', }) setTimeout(function () { wx.hideLoading() }, 3000) _this.startBeaconDiscovery() }, // 失败回调 fail(res) { // console.log(res); wx.showToast({ title: '请开启蓝牙', icon: 'fails', duration: 1000 }) } }) },
2.搜索设备
// 搜索设备 startBeaconDiscovery() { let _this = this; console.log(_this.data.deviceid); wx.startBeaconDiscovery({ uuids:["FDA50693-A4E2-4FB1-AFCF-C6EB07647826", "FDA50693-A4E2-4FB1-AFCF-C6EB07640002", "FDA50693-A4E2-4FB1-AFCF-C6EB07640001", "FDA50693-A4E2-4FB1-AFCF-C6EB07640000"],//获取设备的uuids success(res) { // console.log(res); _this.onBeaconUpdate() } }) },
3.监听搜索设备
// 监听搜索设备 onBeaconUpdate() { let _this = this; wx.onBeaconUpdate(res => { // console.log(res.beacons) _this.getBeacons(); }) },
4.获取已搜索到的设备,判断是否搜索到设备之后停止,
我这里是设置了一个定时器,三秒后停止搜索
// 获取已搜索到的设备 getBeacons() { let _this = this; wx.getBeacons({ success(res) { // console.log(res); for (let i = 0; i < _this.data.data.length; i++) { if (_this.data.data[i].deviceid == _this.data.uids) { _this.setData({ deuids: _this.data.data[i] }) if (_this.data.deuids) { setTimeout(() => { //停止搜索 wx.stopBeaconDiscovery({ success(res) { console.log(res); _this.detaile(); }, fail(res) { console.log(res); } }) }, 3000); } } } } }) },