Page({
data: {
showNav: true,
bluetoothStatus: false
},
openBluetoothAdapter() {
let that = this
wx.openBluetoothAdapter({
success: (res) => {
console.log('蓝牙设备成功', res)
if (res.errMsg == "openBluetoothAdapter:ok") {
that.startBluetoothDevicesDiscovery()
}
},
fail: (res) => {
console.log('蓝牙设备失败', res)
if (res.errCode === 10001) {
that.onBluetoothAdapterStateChange()
}
}
})
},
onBluetoothAdapterStateChange() {
let that = this
wx.onBluetoothAdapterStateChange(function(res) {
console.log('是否开启了蓝牙', res)
if (res.available) {
that.setData({
bluetoothStatus: true
})
that.startBluetoothDevicesDiscovery()
}
})
},
startBluetoothDevicesDiscovery() {
let that = this
wx.startBluetoothDevicesDiscovery({
services: [],
allowDuplicatesKey: false,
success(res) {
console.log('是否处于搜索状态', res)
if (res.errCode == 0) {
that.stopBluetoothDevicesDiscovery()
}
},
fail(res) {
console.log(res)
}
})
},
stopBluetoothDevicesDiscovery() {
let that = this
wx.stopBluetoothDevicesDiscovery({
success(res) {
console.log('停止设备', res)
if (res.errMsg == 'stopBluetoothDevicesDiscovery:ok') {
that.getBluetoothDevices()
}
}
})
},
getBluetoothDevices() {
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.getBluetoothDevices({
success: function(res) {
console.log(res)
if (res.errMsg == 'getBluetoothDevices:ok') {
}
if (res.devices[0]) {
console.log(ab2hex(res.devices[0].advertisData))
}
}
})
},
closeBluetoothAdapter() {
wx.closeBluetoothAdapter({
success(res) {
console.log(res)
}
})
},
onLoad: function(options) {
this.openBluetoothAdapter()
},
})
麻烦在手机微信那里上传下日志: 我->设置->帮助与反馈右上角有个上报日志的入口,麻烦提供一下微信号,时间点
1.如图,我开启蓝牙后,监听的蓝牙列表都是未知设备,而且还少
2.如上面代码,我是在onload中去执行的蓝牙初始化代码,业务场景如下所述:
第一种场景:我的手机蓝牙本身就是开启的,进入真机调试,然后拿到设备列表,这个目前在我调试的过程中是没有问题的。
第二种场景:我的手机蓝牙是关闭状态,我进入调试,然后打开蓝牙,也获取到了蓝牙列表,但是我在当前调试关闭了蓝牙,然后再打开蓝牙就获取不到蓝牙列表了
@社区技术运营专员-小柿子