鸿蒙Next蓝牙搜索设备如何获取deviceid
在鸿蒙Next系统中使用蓝牙搜索设备时,如何获取扫描到的设备的deviceid?我已经尝试了官方文档中的蓝牙API,但找不到直接获取deviceid的方法。请问有具体的代码示例或者需要注意的步骤吗?
2 回复
哈哈,程序员小哥,鸿蒙Next里获取蓝牙设备的deviceid就像找对象的微信号——得先配对成功!调用BluetoothDevice.getDeviceId()就行,记得先通过BluetoothHost扫描到设备对象哦~(别问我为什么知道,说多了都是泪)
更多关于鸿蒙Next蓝牙搜索设备如何获取deviceid的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)中,获取蓝牙设备的deviceId(设备标识符)需要通过蓝牙扫描功能实现。以下是关键步骤和示例代码:
主要步骤
- 申请蓝牙权限:在
module.json5中配置权限。 - 开启蓝牙:确保设备蓝牙已启用。
- 注册扫描回调:监听发现的设备。
- 开始扫描:执行蓝牙设备搜索。
- 获取deviceId:从扫描结果中提取。
示例代码
import { bluetoothManager } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
// 1. 申请权限(module.json5配置)
// "requestPermissions": [
// {
// "name": "ohos.permission.USE_BLUETOOTH",
// "reason": "蓝牙设备扫描"
// }
// ]
// 2. 开启蓝牙(需先检查状态)
async function enableBluetooth(): Promise<void> {
try {
if (!bluetoothManager.isBluetoothAvailable()) {
console.error("蓝牙不可用");
return;
}
await bluetoothManager.enableBluetooth();
} catch (error) {
console.error("开启蓝牙失败: " + JSON.stringify(error));
}
}
// 3. 注册扫描回调并开始扫描
async function startScan(): Promise<void> {
try {
// 注册设备发现监听
bluetoothManager.registerScanCallback({
onScanResult: (result: ScanResult) => {
// 4. 获取deviceId
const deviceId: string = result.device.deviceId;
console.log("发现设备 deviceId: " + deviceId);
// 停止扫描(根据业务需求决定时机)
// bluetoothManager.stopScan();
}
});
// 开始扫描
await bluetoothManager.startScan();
console.log("扫描已开始");
} catch (error) {
console.error("扫描失败: " + JSON.stringify(error));
}
}
// 调用示例
async function main() {
await enableBluetooth();
await startScan();
}
注意事项
- 权限管理:需在应用配置中声明
ohos.permission.USE_BLUETOOTH权限,并在运行时动态申请(API 10+要求)。 - 扫描控制:及时调用
stopScan()避免功耗问题。 - 设备过滤:可通过
scanFilter参数限定扫描条件。
通过以上代码,在onScanResult回调中即可实时获取到每个蓝牙设备的唯一deviceId。

