uniapp搜索蓝牙
uniapp 搜索蓝牙设备的方法
在 uniapp 中搜索蓝牙设备需要使用 uni.startBluetoothDevicesDiscovery API。以下是一个完整的实现流程:
初始化蓝牙模块
uni.openBluetoothAdapter({
success(res) {
console.log('蓝牙模块初始化成功');
// 开始搜索设备
startDiscovery();
},
fail(err) {
console.error('蓝牙模块初始化失败', err);
}
});
开始搜索蓝牙设备
function startDiscovery() {
uni.startBluetoothDevicesDiscovery({
services: [], // 指定要搜索的服务UUID,空数组表示搜索所有设备
allowDuplicatesKey: false, // 是否允许重复上报同一设备
interval: 0, // 上报间隔
success(res) {
console.log('开始搜索蓝牙设备');
// 监听发现新设备事件
uni.onBluetoothDeviceFound(handleDeviceFound);
},
fail(err) {
console.error('搜索失败', err);
}
});
}
处理发现的设备
function handleDeviceFound(res) {
const devices = res.devices;
if (devices.length) {
console.log('发现新设备:', devices);
// 这里可以存储设备列表或更新UI
}
}
停止搜索蓝牙设备
当不需要继续搜索时,应该停止搜索以节省电量:
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log('已停止搜索蓝牙设备');
}
});
获取已发现的设备列表
如果需要获取已经发现的设备列表:
uni.getBluetoothDevices({
success(res) {
console.log('已发现设备列表:', res.devices);
}
});
注意事项
- 在Android平台上,需要先调用
openBluetoothAdapter初始化蓝牙模块 - iOS和Android的蓝牙API行为可能有差异,需要进行兼容性处理
- 搜索前需要确保用户已授权蓝牙权限
- 真机调试时,需要在manifest.json中配置蓝牙权限
完整示例代码
export default {
data() {
return {
devices: []
}
},
methods: {
initBluetooth() {
uni.openBluetoothAdapter({
success: this.startDiscovery,
fail: this.handleError
});
},
startDiscovery() {
uni.startBluetoothDevicesDiscovery({
services: [],
success: () => {
uni.onBluetoothDeviceFound(this.handleDeviceFound);
},
fail: this.handleError
});
},
handleDeviceFound(res) {
this.devices = [...this.devices, ...res.devices];
},
stopDiscovery() {
uni.stopBluetoothDevicesDiscovery();
},
handleError(err) {
console.error('蓝牙操作出错:', err);
}
},
onLoad() {
this.initBluetooth();
},
onUnload() {
this.stopDiscovery();
uni.closeBluetoothAdapter();
}
}
权限配置
在manifest.json中需要添加以下权限:
{
"mp-weixin": {
"appid": "your-appid",
"permission": {
"scope.bluetooth": {
"desc": "需要您的授权才能使用蓝牙功能"
}
}
}
}
以上代码实现了uniapp中蓝牙设备的搜索功能,包括初始化、搜索、停止搜索等完整流程。实际使用时可以根据需求进行修改和扩展。







