本文原创发布在华为开发者社区,更多鸿蒙场景化示例请见华为开发者联盟官网“行业实践与常见问题”专题页。
介绍
本示例使用鸿蒙ohos.distributedDeviceManager模块,实现设备间相互认证的能力。
效果预览
使用说明
- 进入应用会出现是否允许应用发现和连接附近设备的弹窗,点击允许,会获取当前设备的信息并显示在应用首页。
- 点击“搜索周边设备”按钮,会搜索周边未绑定设备,并显示结果。
- 点击“查看已绑定设备”按钮,会以列表形式显示所有可信设备。
实现思路
发现和连接附近设备弹窗
向用户申请权限ohos.permission.DISTRIBUTED_DATASYNC,用户允许后,通过\@ohos.distributedDeviceManager接口获取分布式设备的基本信息,如设备标识符,设备名称等等。核心代码如下,源码参考
Index.ets
async aboutToAppear(): Promise<void> {
// 申请权限 ohos.permission.DISTRIBUTED_DATASYNC
await this.getPermissions('ohos.permission.DISTRIBUTED_DATASYNC')
// 获取hap信息
this.bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
this.getLocalDeviceInfo()
}
搜索周边设备
通过DeviceManager接口获取周边未绑定设备的信息,在调用DeviceManager的方法前,需要先通过createDeviceManager构建一个DeviceManager实例dmInstance。将搜索到的设备信息以列表的信息展示。核心代码如下,源码参考
Index.ets
// 注册发现设备成功回调
this.getDmInstance().on('discoverSuccess', (data) => {
console.log(TAG, `发现周边设备成功 ${JSON.stringify(data.device)}`)
let hasSameDeviceId = false
hasSameDeviceId = this.discoverDeviceList.some(deviceInfo => {
return deviceInfo.deviceId === data.device.deviceId
})
if (!hasSameDeviceId) {
this.discoverDeviceList.push(data.device)
}
})
// 注册发现设备失败回调
this.getDmInstance().on('discoverFailure', (data) => {
console.log(TAG, `发现周边设备失败 ${data.reason}`)
})
const discoverParam: Record<string, number> = {
'discoverTargetType': 1
}
const filterOptions: Record<string, number> = {
'availableStatus': 0 // 仅发现不可信设备
}
try {
this.discoverDeviceList = []
this.getDmInstance().startDiscovering(discoverParam, filterOptions)
this.isSearching = true
console.log(TAG, `开始搜索周边设备`)
} catch (e) {
console.error(TAG, `startDiscovering fail ${e.code} ${e.message}`)
}
}
stopSearch () {
try {
this.getDmInstance().stopDiscovering()
console.log(TAG, `停止搜索`)
} catch (e) {
console.error(TAG, `停止搜索失败 ${e.code} ${e.message}`)
}
this.isSearching = false
}
getDmInstance (): deviceManager.DeviceManager {
if (this.dmInstance) {
return this.dmInstance
}
this.dmInstance = deviceManager.createDeviceManager(this.bundleInfo?.name)
return this.dmInstance
}
查看已绑定设备
利用getAvailableDeviceListSync接口同步获取所有可信设备列表。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。