推荐答案
wx.getBluetoothDevices({
success: function(res) {
console.log('已发现的蓝牙设备列表:', res.devices);
},
fail: function(err) {
console.error('获取蓝牙设备失败:', err);
}
});本题详细解读
1. wx.getBluetoothDevices 的作用
wx.getBluetoothDevices 是微信小程序提供的 API,用于获取所有已发现的蓝牙设备。这些设备包括已经连接的和未连接的设备。
2. 参数说明
success: 成功回调函数,返回一个包含devices数组的对象,数组中每个元素都是一个蓝牙设备的信息。fail: 失败回调函数,返回错误信息。
3. 返回的蓝牙设备信息
res.devices 是一个数组,每个元素包含以下字段:
name: 蓝牙设备名称。deviceId: 蓝牙设备 ID。RSSI: 信号强度。advertisData: 广播数据。advertisServiceUUIDs: 广播服务 UUID 列表。localName: 本地名称。serviceData: 服务数据。
4. 使用场景
- 在需要列出所有已发现的蓝牙设备时使用。
- 通常在调用
wx.startBluetoothDevicesDiscovery开始搜索蓝牙设备后使用。
5. 注意事项
- 需要在小程序配置文件中声明
bluetooth权限。 - 在调用
wx.getBluetoothDevices之前,确保已经调用wx.openBluetoothAdapter初始化蓝牙适配器。
6. 示例代码解释
wx.getBluetoothDevices({
success: function(res) {
console.log('已发现的蓝牙设备列表:', res.devices);
},
fail: function(err) {
console.error('获取蓝牙设备失败:', err);
}
});success回调函数中,res.devices包含了所有已发现的蓝牙设备信息。fail回调函数中,err包含了失败的错误信息。