核心代码解释申请分布式数据同步权限。发现周边不可信设备。建立设备间的可信关系。查询周围上线并且可行的设备。核心代码如下:Button("startMonitor") .onClick(() => { try { //这里构造一个对象并赋值,原因是同一个包名构造的对象并不是单例的 this.dmInstance = deviceManager.createDeviceManager("com.example.test_240220184822040") this.myDeviceId = this.dmInstance.getLocalDeviceId() this.dmInstance.on('discoverSuccess', (data) => { console.log('testTag - discoverSuccess on:' + JSON.stringify(data)) //若deviceId等于目标id,则与该设备绑定信任关系 181cfec6c9e18c41 f7c2338a316948a5 if (data.device.deviceId == "f7c2338a316948a5") { //绑定信任设备所需options,即绑定的验证方式,本例为pin码方式验证 let bindParam: Record<string, string | number> = { 'bindType': 1, // 认证类型: 1 - 无帐号PIN码认证 }; //回调数据对象,绑定成功后回调的对象封装 class Data { deviceId: string = ''; } //绑定信任关系所用接口 this.dmInstance!.bindTarget(data.device.deviceId, bindParam, (_err: BusinessError, data: Data) => { console.info('testTag - bindTarget result:' + JSON.stringify(data)); }) } hilog.info(0x0000, 'testTag', '%{public}s', JSON.stringify(data)); }); } catch (err) { let e: BusinessError = err as BusinessError; console.error('testTag - createDeviceManager errCode:' + e.code + ',errMessage:' + e.message); } }) Text("myDeviceId - " + this.myDeviceId) .id('message') .textAlign(TextAlign.Center) .width('100%') .fontSize(15) .copyOption(CopyOptions.LocalDevice) .size({ width: '95%', height: '75%' }) .border({ width: 1, radius: 20, color: Color.Black }) .padding(10) .margin({ top: 16 }) Button("startDiscover").onClick(() => { let discoverParam: Record<string, number> = { 'discoverTargetType': 1 }; let filterOptions: Record<string, number> = { 'availableStatus': 0 }; try { this.dmInstance!.startDiscovering(discoverParam, filterOptions); } catch (err) { let e: BusinessError = err as BusinessError; console.error('testTag - startDiscovering errCode:' + e.code + ',errMessage:' + e.message); } this.flagA = false this.flagB = true }).enabled(this.flagA) Button("stopDiscover").onClick(() => { try { this.dmInstance!.stopDiscovering() } catch (err) { let e: BusinessError = err as BusinessError; console.error('testTag - stopDiscovering errCode:' + e.code + ',errMessage:' + e.message); } this.flagA = true this.flagB = false }).enabled(this.flagB) Button("getAvailableDeviceList").onClick(() =>{ try { let deviceInfoList: Array<deviceManager.DeviceBasicInfo> = this.dmInstance!.getAvailableDeviceListSync(); console.log("testTag - deviceInfoList: " + JSON.stringify(deviceInfoList)) } catch (err) { let e: BusinessError = err as BusinessError; console.error('testTag - getAvailableDeviceListSync errCode:' + e.code + ',errMessage:' + e.message); } })总结:发现周围终端设备并上报。周围设备需要连接同局域网或者同时打开蓝牙,可以根据设备类型、距离、设备是否可信等进行筛选;不同设备协同合作完成分布式业务的前提是设备间可信,对于周边发现的不可信设备,可通过绑定使彼此建立可信关系,提供pin码、碰、扫、靠等设备认证框架,支持对接各种认证交互接口。:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/devicemanager-guidelines-0000001774120506实现效果注明适配的版本信息IDE:DevEco Studio 4.1.3.500SDK:HarmoneyOS 4.0.10.11
核心代码解释
核心代码如下:
总结:
实现效果
注明适配的版本信息