uniapp 蓝牙配对如何实现
在uniapp中如何实现蓝牙配对功能?我尝试使用uni.openBluetoothAdapter初始化蓝牙模块,但不知道后续如何进行设备搜索、配对和连接。具体需要调用哪些API?配对过程中是否需要处理权限问题?能否提供一个完整的代码示例?
2 回复
在uniapp中,使用uni.createBLEConnection连接设备,监听onBLEConnectionStateChange事件获取配对状态。配对成功后即可通信。
在 UniApp 中实现蓝牙配对,主要通过调用 uni-app 提供的蓝牙 API 完成设备发现、连接和通信。以下是关键步骤及示例代码:
1. 初始化蓝牙模块
uni.openBluetoothAdapter({
success: (res) => {
console.log('蓝牙模块初始化成功');
this.startBluetoothDiscovery();
},
fail: (err) => {
console.error('初始化失败:', err);
}
});
2. 搜索蓝牙设备
startBluetoothDiscovery() {
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('开始搜索设备');
// 监听寻找到新设备的事件
uni.onBluetoothDeviceFound(this.onDeviceFound);
}
});
}
3. 发现设备并获取信息
onDeviceFound(devices) {
devices.devices.forEach(device => {
if (device.name && device.deviceId) {
console.log('发现设备:', device.name, device.deviceId);
// 可在此处过滤目标设备(如通过设备名称)
}
});
}
4. 连接设备并配对
// 选择设备后建立连接
connectDevice(deviceId) {
uni.createBLEConnection({
deviceId,
success: (res) => {
console.log('连接成功');
this.getServices(deviceId); // 获取服务
},
fail: (err) => {
console.error('连接失败:', err);
}
});
}
5. 获取服务与特征值
getServices(deviceId) {
uni.getBLEDeviceServices({
deviceId,
success: (res) => {
res.services.forEach(service => {
this.getCharacteristics(deviceId, service.uuid);
});
}
});
}
getCharacteristics(deviceId, serviceId) {
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
res.characteristics.forEach(char => {
// 根据 properties 判断读写权限,进行数据交互
if (char.properties.write) {
// 示例:写入数据
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: char.uuid,
value: ArrayBuffer.from('Hello'),
});
}
});
}
});
}
6. 监听数据接收
uni.onBLECharacteristicValueChange((res) => {
console.log('收到数据:', new Uint8Array(res.value));
});
注意事项:
- 权限配置:在
manifest.json中配置蓝牙权限(App 平台需勾选蓝牙权限)。 - 设备过滤:通过
device.name或本地存储的deviceId识别目标设备。 - 错误处理:在所有 API 调用中补充
fail回调处理异常。 - 平台差异:Android 可能需位置权限,iOS 需在系统设置中手动配对。
简化流程:
- 初始化蓝牙 → 2. 搜索设备 → 3. 选择设备连接 → 4. 发现服务/特征 → 5. 读写数据。
通过以上步骤即可在 UniApp 中完成蓝牙配对与通信。

