uniapp搜索蓝牙
搜索蓝牙设备
在UniApp中搜索蓝牙设备需要使用uni.startBluetoothDevicesDiscovery方法。该方法会开始搜索附近的蓝牙设备,搜索到的设备可以通过onBluetoothDeviceFound事件监听获取。
uni.startBluetoothDevicesDiscovery({
success: function(res) {
console.log('开始搜索蓝牙设备', res);
},
fail: function(err) {
console.error('搜索蓝牙设备失败', err);
}
});
uni.onBluetoothDeviceFound(function(devices) {
console.log('发现新设备', devices);
});
获取已发现的设备列表
使用uni.getBluetoothDevices方法可以获取已经发现的蓝牙设备列表。该方法返回一个数组,包含所有已发现的设备信息。

uni.getBluetoothDevices({
success: function(res) {
console.log('已发现的设备列表', res.devices);
},
fail: function(err) {
console.error('获取设备列表失败', err);
}
});
停止搜索蓝牙设备
当不需要继续搜索蓝牙设备时,可以调用uni.stopBluetoothDevicesDiscovery方法停止搜索。
uni.stopBluetoothDevicesDiscovery({
success: function(res) {
console.log('停止搜索蓝牙设备', res);
},
fail: function(err) {
console.error('停止搜索失败', err);
}
});
连接蓝牙设备
发现目标设备后,可以使用uni.createBLEConnection方法连接设备。需要传入设备的deviceId。

uni.createBLEConnection({
deviceId: '目标设备的deviceId',
success: function(res) {
console.log('连接设备成功', res);
},
fail: function(err) {
console.error('连接设备失败', err);
}
});
获取蓝牙设备服务
连接成功后,使用uni.getBLEDeviceServices方法获取设备的服务列表。
uni.getBLEDeviceServices({
deviceId: '目标设备的deviceId',
success: function(res) {
console.log('获取服务列表成功', res.services);
},
fail: function(err) {
console.error('获取服务列表失败', err);
}
});
监听蓝牙连接状态
通过onBLEConnectionStateChange方法可以监听蓝牙设备的连接状态变化。
uni.onBLEConnectionStateChange(function(res) {
console.log('设备连接状态变化', res.connected);
});
注意事项
- 使用蓝牙功能前需要确保用户已授权蓝牙权限。
- 不同平台的实现可能有差异,建议测试时覆盖目标平台。
- 搜索到的设备信息包含
deviceId、name、RSSI等字段,具体字段可能因平台而异。 - 长时间搜索会消耗较多电量,建议在找到目标设备后及时停止搜索。






