炉石传说佣兵战记自动化脚本终极指南:5步轻松告别重复操作
2026/5/8 17:50:56
鸿蒙分布式应用开发实战:构建跨设备协同生态
✅学习目标
💡重点内容
鸿蒙分布式能力栈、设备发现API、跨设备页面跳转、分布式数据同步、协同应用架构
⚠️前置基础
已掌握鸿蒙ArkTS开发、页面交互、数据持久化、应用签名等核心技术,了解DevEco Studio高级操作
鸿蒙分布式软总线是实现设备间无缝连接的基础,提供以下核心能力:
核心API:@ohos.distributedHardware.deviceManager
实现多设备间数据一致性的核心服务:
核心API:@ohos.data.distributedData
实现跨设备的页面协同与共享:
核心API:@ohos.distributedUiAccess
构建一个支持手机+智能手表的分布式待办应用:
在entry/config.json中添加分布式能力所需权限:
"module":{"reqPermissions":[{"name":"ohos.permission.DISTRIBUTED_DATASYNC","usedScene":{"abilities":["*"],"when":"inuse"}},{"name":"ohos.permission.GET_DISTRIBUTED_DEVICE_INFO","usedScene":{"abilities":["*"],"when":"inuse"}},{"name":"ohos.permission.DISTRIBUTED_DEVICE_STATE_CHANGE","usedScene":{"abilities":["*"],"when":"inuse"}}]}// utils/DeviceManager.ts import { DeviceManager, DeviceInfo } from '@ohos.distributedHardware.deviceManager'; export class DeviceManagerUtil { private static instance: DeviceManagerUtil; private deviceManager: DeviceManager | null = null; private connectedDevices: DeviceInfo[] = []; // 单例模式 public static getInstance(): DeviceManagerUtil { if (!DeviceManagerUtil.instance) { DeviceManagerUtil.instance = new DeviceManagerUtil(); } return DeviceManagerUtil.instance; } // 初始化设备管理器 public async initDeviceManager(): Promise<DeviceManager> { if (this.deviceManager) { return this.deviceManager; } return new Promise((resolve, reject) => { try { const context = getContext(this) as common.UIAbilityContext; const loadDeviceManager = () => { this.deviceManager = DeviceManager.createDeviceManager(context.bundleName); if (this.deviceManager) { resolve(this.deviceManager); } else { reject(new Error('设备管理器创建失败')); } }; DeviceManager.on('loadSuccess', loadDeviceManager); DeviceManager.on('loadFailed', () => { reject(new Error('设备管理器加载失败')); }); } catch (error) { reject(error); } }); } // 发现可连接设备 public async discoverDevices(): Promise<DeviceInfo[]> { const dm = await this.initDeviceManager(); return new Promise((resolve) => { const onDeviceFound = (device: DeviceInfo) => { if (device.deviceType === 'smart_watch' && !this.connectedDevices.some(d => d.deviceId === device.deviceId)) { this.connectedDevices.push(device); } }; // 监听设备发现事件 dm.on('deviceFound', onDeviceFound); // 开始发现设备 dm.startDeviceDiscovery({}); // 5秒后停止发现 setTimeout(() => { dm.stopDeviceDiscovery({}); dm.off('deviceFound', onDeviceFound); resolve(this.connectedDevices); }, 5000); }); } }// utils/DistributedKV.ts import { KVManager, KVStore, KVStoreConfig } from '@ohos.data.distributedData'; export class DistributedKVUtil { private static instance: DistributedKVUtil; private kvManager: KVManager | null = null; private kvStore: KVStore | null = null; public static getInstance(): DistributedKVUtil { if (!DistributedKVUtil.instance) { DistributedKVUtil.instance = new DistributedKVUtil(); } return DistributedKVUtil.instance; } // 初始化KV管理器 public async initKVManager(): Promise<KVManager> { if (this.kvManager) { return this.kvManager; } const config: KVStoreConfig = { bundleName: getContext(this).bundleName, context: getContext(this) as common.UIAbilityContext, // 分布式模式 mode: KVStoreConfig.Mode.SINGLE_PROCESS_MODE }; this.kvManager = await KVManager.createKVManager(config); return this.kvManager; } // 打开分布式KV存储 public async openKVStore(): Promise<KVStore> { if (this.kvStore) { return this.kvStore; } const manager = await this.initKVManager(); this.kvStore = await manager.getKVStore<KVStore>({ storeId: 'todo_distributed_store', options: { createIfMissing: true, encrypt: true, backup: true, // 开启分布式同步 syncable: true } }); // 监听数据变化 this.kvStore.on('dataChange', (data) => { console.log('分布式数据变化:', data); }); return this.kvStore; } // 保存待办事项 public async putTodoItem(item: TodoItem): Promise<void> { const store = await this.openKVStore(); await store.put(`todo_${item.id}`, JSON.stringify(item)); } // 获取所有待办事项 public async getAllTodoItems(): Promise<TodoItem[]> { const store = await this.openKVStore(); const result = await store.getAll(); return Object.values(result).map((value) => JSON.parse(value as string) as TodoItem); } // 更新待办事项状态 public async updateTodoStatus(id: number, completed: boolean): Promise<void> { const store = await this.openKVStore(); const itemStr = await store.get(`todo_${id}`) as string; const item = JSON.parse(itemStr) as TodoItem; item.completed = completed; await store.put(`todo_${id}`, JSON.stringify(item)); } }// pages/PhoneTodoListPage.ets @Entry @Component struct PhoneTodoListPage { @State todoList: TodoItem[] = []; @State inputContent: string = ''; @State devices: DeviceInfo[] = []; private kvUtil = DistributedKVUtil.getInstance(); private deviceUtil = DeviceManagerUtil.getInstance(); async onPageShow() { // 初始化分布式存储 await this.kvUtil.openKVStore(); // 加载待办事项 this.todoList = await this.kvUtil.getAllTodoItems(); // 发现设备 this.devices = await this.deviceUtil.discoverDevices(); } // 添加待办事项 async addTodoItem() { if (!this.inputContent.trim()) return; const newTodo: TodoItem = { id: Date.now(), content: this.inputContent.trim(), completed: false, createTime: new Date().toISOString() }; // 保存到分布式存储 await this.kvUtil.putTodoItem(newTodo); // 更新本地列表 this.todoList.unshift(newTodo); // 清空输入框 this.inputContent = ''; // 提示成功 prompt.showToast({ message: '待办已添加,将同步到所有设备' }); } // 跨设备跳转 async jumpToWatch(device: DeviceInfo) { try { const context = getContext(this) as common.UIAbilityContext; // 跨设备启动页面 await distributedUiAccess.startAbility({ bundleName: context.bundleName, abilityName: 'WatchTodoDetailAbility', deviceId: device.deviceId, parameters: { todoList: JSON.stringify(this.todoList) } }); prompt.showToast({ message: '已跳转到手表端' }); } catch (error) { console.error('跨设备跳转失败:', error); prompt.showToast({ message: '跳转失败' }); } } build() { Column({ space: 20 }) { // 顶部导航 Row() { Text('分布式待办事项') .fontSize(28) .fontWeight(FontWeight.Bold); } .padding(24) .width('100%'); // 设备连接状态 if (this.devices.length > 0) { Text(`已发现设备: ${this.devices[0].deviceName}`) .fontSize(16) .fontColor('#007DFF') .onClick(() => this.jumpToWatch(this.devices[0])); } // 输入框与添加按钮 Row({ space: 12 }) { TextInput({ placeholder: '输入待办内容' }) .width(260) .height(44) .backgroundColor(Color.White) .onChange(value => this.inputContent = value); Button('添加待办') .width(100) .height(44) .backgroundColor('#007DFF') .fontColor(Color.White) .onClick(() => this.addTodoItem()); } .padding(24); // 待办列表 List({ space: 12 }) { ForEach(this.todoList, item => { ListItem() { Row({ space: 16 }) { Checkbox() .checked(item.completed) .onChange(async isChecked => { await this.kvUtil.updateTodoStatus(item.id, isChecked); // 更新本地状态 item.completed = isChecked; }); Text(item.content) .fontSize(18) .textDecoration({ type: item.completed ? TextDecorationType.LineThrough : TextDecorationType.None }); } .width('100%') .padding(20) .backgroundColor(Color.White) .borderRadius(12); } }, item => item.id); } .width('100%') .height('60%') .padding({ left: 24, right: 24 }); } .width('100%') .height('100%') .backgroundColor('#F8F9FA'); } }// watch/pages/WatchTodoListPage.ets @Entry @Component struct WatchTodoListPage { @State todoList: TodoItem[] = []; private kvUtil = DistributedKVUtil.getInstance(); async onPageShow() { // 初始化分布式存储 await this.kvUtil.openKVStore(); // 加载待办事项 this.todoList = await this.kvUtil.getAllTodoItems(); // 监听数据变化 this.kvUtil.openKVStore().then(store => { store.on('dataChange', () => { this.loadTodoList(); }); }); } // 加载待办事项 async loadTodoList() { this.todoList = await this.kvUtil.getAllTodoItems(); } // 更新待办状态 async updateTodoStatus(id: number, completed: boolean) { await this.kvUtil.updateTodoStatus(id, completed); } build() { Column({ space: 12 }) { Text('待办事项') .fontSize(20) .fontWeight(FontWeight.Bold) .margin({ top: 20 }); // 待办列表 List({ space: 8 }) { ForEach(this.todoList, item => { ListItem() { Row({ space: 10 }) { Checkbox() .checked(item.completed) .onChange(async isChecked => { await this.updateTodoStatus(item.id, isChecked); }); Text(item.content) .fontSize(14) .maxLines(1) .overflow(TextOverflow.Ellipsis); } .width('100%') .padding(12) .backgroundColor(Color.White) .borderRadius(8); } }, item => item.id); } .width('100%') .height('80%') .padding({ left: 12, right: 12 }); } .width('100%') .height('100%') .backgroundColor('#F8F9FA'); } }问题:调用discoverDevices()后未发现任何设备
解决方案:
DISTRIBUTED_DEVICE_INFO等权限问题:手机添加待办后,手表端长时间未同步
解决方案:
syncable选项是否开启store.sync()手动触发同步问题:调用startAbility()后提示“设备未连接”
解决方案:
DISTRIBUTED_UI_ACCESS已申请问题:运行时未弹出权限申请对话框
解决方案:
config.json中正确配置权限的usedScene@ohos.abilityAccessCtrl.requestPermissionsFromUser手动申请权限通过本章学习,我们掌握了:
鸿蒙分布式能力是未来智能生态的核心趋势,掌握分布式应用开发将帮助你构建更具竞争力的跨设备应用。通过不断实践与创新,你将在鸿蒙生态开发中占据领先地位!