在使用uniapp开发小程序时,需要搜索附近的蓝牙设备,使用wx.startBluetoothDevicesDiscovery开启搜索蓝牙设备成功后,使用 wx.onBluetoothDeviceFound进行监听,,第一次进入界面可以监听到,但是返回上一级页面再次开启搜索蓝牙设备成功后进行监听,无法监听到任何设备,这是哪里的问题呢?
代码如下
<template>
<view>
<view v-for="(item,index) in equipmentList" :key="index">
<view class="ble-name" @click="chooseEquipment(item)">
{{item.name}}
<view class="ble-split"></view>
</view>
</view>
<!-- 提示窗示例 -->
<uni-popup ref="alertDialog" type="dialog">
<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="已打开" title="警告" content="请打开蓝牙"
@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
</uni-popup>
</view>
</template>
<script>
export default {
data() {
return {
imageBaseUrl: '',
equipmentList: [],
userInfo: '',
msgType: '',
}
},
onLoad() {
let that = this
wx.getSetting({
success(res) {
//判断是否有'scope.bluetooth'属性
if (res.authSetting.hasOwnProperty('scope.bluetooth')) {
//'scope.bluetooth'属性存在,且为false
if (!res.authSetting['scope.bluetooth']) {
//弹窗授权
wx.openSetting({
success(res) {
console.log(res.authSetting)
}
})
}
} else {
console.log("cd")
//'scope.bluetooth'属性不存在,需要授权
wx.authorize({
scope: 'scope.bluetooth',
success() {
// 用户已经同意小程序使用手机蓝牙功能,后续调用 蓝牙 接口不会弹窗询问
console.log(res.authSetting)
}
})
}
}
})
console.log(43544656)
this.equipmentList = []
wx.openBluetoothAdapter({
success(res) {
console.log("初始化蓝牙模块成功", res)
that.getAllEquipments()
},
fail(erro) {
if (erro.errCode == 10001) {
that.msgType = 'error'
that.$refs.alertDialog.open()
}
}
})
},
onShow() {
this.equipmentList = []
},
onBackPress() {
this.equipmentList = []
uni.stopBluetoothDevicesDiscovery({
success(res2) {
console.log('停止成功')
console.log(res2)
},
fail(err) {
console.log('停止失败')
console.error(err)
}
})
},
methods: {
dialogConfirm(e) {
console.log(e)
},
dialogClose(e) {
console.log(e)
},
getAllEquipments() {
let that = this
wx.startBluetoothDevicesDiscovery({
success(res) {
console.log("开启搜索蓝牙设备", res)
wx.onBluetoothDeviceFound(function(res1) {
var devices = res1.devices;
console.log(devices[0].name)
if (devices[0].name != '' && devices[0].name != null) {
console.log("新的设备")
console.log(devices[0].name)
that.equipmentList.push(devices[0])
that.$forceUpdate()
}
})
},
fail(err1) {
console.log("搜索失败", err1)
}
})
},
chooseEquipment(e) {
wx.createBLEConnection({
deviceId: e.deviceId,
success(res1) {
console.log(res1)
console.log("连接成功!")
uni.stopBluetoothDevicesDiscovery({
success(res2) {
console.log('停止成功')
console.log(res2)
uni.navigateTo({
url: '/pages/equipment/equipment?item=' + encodeURIComponent(
JSON.stringify(e))
})
},
fail(err) {
console.log('停止失败')
console.error(err)
}
})
}
})
},
ab2hex(buffer) {
var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
return ('00' + bit.toString(16)).slice(-2)
})
return hexArr.join('');
}
}
}
</script>
<style>
.ble-name {
margin-left: 10px;
height: 32px;
line-height: 32px;
font-size: 16px;
width: calc(100% - 20px);
margin-top: 10px;
}
.ble-split {
width: 100%;
height: 1px;
background-color: #C4C4C4;
}
</style>