1、初始化蓝牙设备 uni.openBluetoothAdapter
// 初始化蓝牙模块
initBluetooth() {
uni.openBluetoothAdapter({
success: (res) => {
console.log('初始化蓝牙成功', res); //蓝牙开启成功
},
fail: (err) => {
console.error('初始化蓝牙失败', err); //蓝牙开启失败
uni.showToast({
title: err
})
},
});
},
2、搜索蓝牙设备 uni.startBluetoothDevicesDiscovery
// 搜索蓝牙设备
startScan() {
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('搜索设备成功', res);
// 监听寻找到新设备的事件
uni.onBluetoothDeviceFound((devices) => {
devices.devices.forEach(device => {
this.devices.push(device);
console.log('发现蓝牙设备:', device)
});
});
},
fail: (err) => {
console.error('扫描失败', err);
},
});
// 定时停止搜索,避免长时间搜索占用系统资源
setTimeout(() => {
uni.stopBluetoothDevicesDiscover