π·οΈ Huawei Hongmeng Stage model practical combat: building a super application that combines devices and collaborates
As a developer who has been busy in multi-device development, today I want to share the ultimate practical battle of the Stage model!The smart home APP made with this solution can control mobile phones, tablets, and watches at the same time. Now, the "clearance secrets" of cross-device collaboration are fully disclosed~
1. Multi-device Collaboration: The "Distributed Stage" of the Stage Model
1. Equipment role division (analogous to band division)
Device Type
Role Positioning
Stage Model Application
Mobile
Lead singer (interactive core)
Main Stage, manage global status
Tablet
Guitarist (large screen display)
Substage Stage, extended display content
Watch
Drummer (data acquisition)
ExtensionAbility, real-time data acquisition
Smart speakers
Bassist (voice interaction)
ServiceExtension, backend service
2. Core capabilities of distributed stages
Components cross-device migration: Stage is like a mobile stage, and components can "tour" between devices
Real-time data synchronization: Data between the Stage of each device is like a tacit cooperation between band members
Task Intelligent Scheduling: Assign tasks according to device capabilities, such as calculating the heart rate of the watch, and displaying the results on the mobile phone
2. System architecture: "Building a Blueprint" for the distributed stage
import{distributedDevice}from'@kit.DistributedDeviceKit';// Discover peripheral equipment (like a band looking for teammates)distributedDevice.discoverDevices().then((devices)=>{devices.forEach((device)=>{console.log(`Discover device: ${device.deviceId}, type: ${device.deviceType}`);// Assign Stage roles according to device typeif (device.deviceType==='phone'){this.assignMainStage(device);}elseif (device.deviceType==='tablet'){this.assignExtensionStage(device);}});});// Connect the deviceasyncfunctionconnectToDevice(deviceId:string){constresult=awaitdistributedDevice.connect(deviceId);if (result){console.log(`Successfully connected to device: ${deviceId}`);}}
3. Stage model cross-device application: component "tournament"
1. Main Stage (mobile terminal): Stage Commander
import{UIAbility,distributedTask}from'@ohos.app.ability';exportdefaultclassMainStageextendsUIAbility{onCreate(){console.log('Main Stage starts, starts assignment of tasks');// Assign display tasks to the tablet (like the lead singer to part of the guitarist)this.assignTabletTask();// Assign data acquisition tasks to the watchthis.assignWatchTask();}assignTabletTask(){// Find available tabletsdistributedDevice.findDeviceByType('tablet').then((tabletId)=>{if (tabletId){// Start Stage across devices (send a show invitation to the tablet)constwant={deviceId:tabletId,bundleName:'com.example.multidevice',abilityName:'TabletStage'};distributedTask.startAbility(want);}});}}
2. Substage Stage (tablet): large screen display
import{UIAbility}from'@ohos.app.ability';exportdefaultclassTabletStageextendsUIAbility{onStart(want){console.log('Plate Stage starts, receives the main Stage task');// Subscribe to the main Stage data (like the guitarist listening to the lead singer's rhythm)this.subscribeMainStageData();}subscribeMainStageData(){consteventHub=this.context.eventHub;eventHub.on('mainStageData',(data)=>{// Update the flat panel display (play the guitar according to the lead vocal rhythm)this.updateDisplay(data);});}}
4. Distributed task scheduling: the "conductor" of the stage
1. Task assignment strategy (analogous to band conductor)
Task Type
Assignment Principles
Implementation Method
High computing tasks
Give devices with strong computing power (tablet/mobile phone)
distributedTask.assign
Real-time data acquisition
Give to nearby equipment (watch/bracelet)
Priority allocation after equipment is discovered
Display tasks
Give large screen devices (flat-panel/TV)
Select equipment based on screen size
2. Task Scheduling Practical Code
import{distributedTask}from'@kit.DistributedTaskKit';classTaskScheduler{scheduleTask(taskType:string,data:any){// Check the list of available devices (such as conductors to see the status of band members)distributedDevice.getOnlineDevices().then((devices)=>{//Select equipment according to the task type (the command decides who will play)consttargetDevice=this.chooseDeviceByTaskType(taskType,devices);if (targetDevice){// Assign tasks (command command)distributedTask.schedule({deviceId:targetDevice.id,taskName:taskType,taskData:data}).then(()=>{console.log(`task${taskType} has been assigned to device${targetDevice.id}`);});}});}chooseDeviceByTaskType(taskType:string,devices:Device[]){// High computing tasks for tabletsif (taskType==='highCompute'){returndevices.find(d=>d.deviceType==='tablet');}// Collect it in real time for the watchif (taskType==='realtimeCollect'){returndevices.find(d=>d.deviceType==='wearable');}// Default to mobile phonereturndevices.find(d=>d.deviceType==='phone');}}
5. Cross-device UI adaptation: "Variety Magic" of Stage Set
1. Responsive layout (different equipment and different sets)
@Entry@ComponentstructCrossDeviceLayout{@StatedeviceType:string='phone';build(){Column(){// Mobile layout (small stage set)if (this.deviceType==='phone'){Text('Mobile Interface').fontSize(20)Button('Send to Tablet').onClick(()=>this.sendToTablet())}// Tablet end layout (large stage set)elseif (this.deviceType==='tablet'){Grid(){Text('Big interface of tablet end').gridArea('header')List(){// Large list layout...}.gridArea('content')}.columnsTemplate('1fr').rowsTemplate('50px 1fr').gridAreas('"header" "content"')}}.width('100%').height('100%').onPageShow(()=>{this.detectDeviceType();// Change the set of detection device type})}detectDeviceType(){// Detect the current device typethis.deviceType=distributedDevice.getLocalDeviceType();}}
// Migrate components to tablet in the main StagefunctionmigrateComponentToTablet(){constwant={deviceId:'tablet123',bundleName:'com.example.app',abilityName:'TabletAbility',parameters:{componentData:this.componentData// Pass component data}};// Start the tablet Stage and pass component data (the actor takes props to the tablet stage)distributedTask.startAbility(want);}
6. Data synchronization: "Score Sharing" between stages
1. Distributed Data Center Design
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
β Mobile Data Center ββββββββββ Tablet Data Center βββββββββ Watch Data Center β
β (AppStorage) β β (AppStorage) β β (LocalStorage) β
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
β Data synchronization service β β Conflict resolution module β β Local caching policy β
βββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββ
2. Real-time synchronization of practical code
import{distributedData}from'@kit.DistributedDataKit';// Initialize the distributed data centerclassDataCenter{constructor(){// Start the data synchronization service (like the band unified score)this.initSyncService();// Subscribe to changes in data of each devicethis.subscribeDeviceData();}initSyncService(){distributedData.init({syncInterval:500,// 500ms synchronize onceconflictResolver:this.resolveConflict// Conflict Resolution Function});}subscribeDeviceData(){// Subscribe to mobile datadistributedData.subscribe('phoneData',(data)=>{this.updateAllDevices('phoneData',data);});// Subscribe to tablet datadistributedData.subscribe('tabletData',(data)=>{this.updateAllDevices('tabletData',data);});}updateAllDevices(key:string,data:any){// Synchronize data to all devices (band members synchronize scores)distributedData.syncToAll(key,data);}}
7. Security and Permissions: The "Security Check System" of the Stage
8. Practical case: Smart home cross-device control
1. Scene description
Turn on "Home Mode" on your phone, and at the same time:
β Flat panel display welcome interface
β Watch reminds that the door lock is open
β Smart speakers play welcome voice
2. Stage model implementation
// Mobile phone main Stage (Commander General)onClickHomeMode(){// Send instructions to tablets (Tablet Stage displays the welcome page)this.sendToTablet({type:'welcomePage'});// Give instructions to watches (watch Extension reminder)this.sendToWatch({type:'unlockAlert'});// Send commands to the speaker (speaker service plays voice)this.sendToSpeaker({type:'welcomeVoice'});}// Cross-device command sendingsendToDevice(deviceId:string,command:any){constwant={deviceId,bundleName:'com.example.smartHome',parameters:{command}};distributedTask.startAbility(want);}
9. Performance optimization: "Efficient operation" of the stage
When I used the Stage model to make multiple device applications for the first time, the data between devices was not synchronized for three days. Now I use a distributed data center + EventHub, and cross-device synchronization is as smooth as local operation. It is recommended that novices start with small scenarios, such as simple collaboration between mobile phones and watches, and then gradually expand.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)