讀取藍(lán)牙設(shè)備主要邏輯步驟
1、初始化藍(lán)牙
2、開始搜尋附近的藍(lán)牙外圍設(shè)備
3、監(jiān)聽尋找到新設(shè)備的事件
4、獲取在藍(lán)牙模塊生效期間所有已發(fā)現(xiàn)的藍(lán)牙設(shè)備
<script>
export default {
onLoad() {
//在頁面加載時(shí)候初始化藍(lán)牙適配器
uni.openBluetoothAdapter({
success: e => {
console.log('初始化藍(lán)牙成功:' + e.errMsg);
this.$data.isOpenBle = true;
console.log(this.$data.isOpenBle);
// 初始化完畢開始搜索
this.startBluetoothDeviceDiscovery()
},
fail: e => {
console.log('初始化藍(lán)牙失敗,錯(cuò)誤碼:' + (e.errCode || e.errMsg));
}
});
},
methods: {
startBluetoothDeviceDiscovery() {
//在頁面顯示的時(shí)候判斷是都已經(jīng)初始化完成藍(lán)牙適配器若成功,則開始查找設(shè)備
let self = this;
setTimeout(function() {
if (self.isOpenBle) {
console.log("開始搜尋智能設(shè)備");
uni.startBluetoothDevicesDiscovery({
success: res => {
self.onBluetoothDeviceFound();
},
fail: res => {
console.log("查找設(shè)備失敗!");
uni.showToast({
icon: "none",
title: "查找設(shè)備失敗!",
duration: 3000
})
}
});
} else {
console.log("未初始化藍(lán)牙是配飾器:" + self.isOpenBle);
}
}, 300);
},
/**
* 停止搜索藍(lán)牙設(shè)備
*/
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery({
success: e => {
console.log('停止搜索藍(lán)牙設(shè)備:' + e.errMsg);
},
fail: e => {
console.log('停止搜索藍(lán)牙設(shè)備失敗,錯(cuò)誤碼:' + e.errCode);
}
});
},
/**
* 發(fā)現(xiàn)外圍設(shè)備
*/
onBluetoothDeviceFound() {
console.log("監(jiān)聽尋找新設(shè)備");
// this.getBluetoothDevices();
uni.onBluetoothDeviceFound(devices => {
console.log('開始監(jiān)聽尋找到新設(shè)備的事件');
this.getBluetoothDevices();
});
},
/**
* 獲取在藍(lán)牙模塊生效期間所有已發(fā)現(xiàn)的藍(lán)牙設(shè)備。包括已經(jīng)和本機(jī)處于連接狀態(tài)的設(shè)備。
*/
getBluetoothDevices() {
console.log("獲取藍(lán)牙設(shè)備");
uni.getBluetoothDevices({
success: res => {
console.log('獲取藍(lán)牙設(shè)備成功:' + res.errMsg);
console.log(res)
}
});
}
}
}
</script>