1# Cross-Device Migration 2 3## Overview 4 5When the environment changes, for example, when a user goes outdoors or when a more appropriate device is detected, the user can migrate an ongoing task to another device for better experience. The application on the source device can automatically exit, depending on the setting. A typical cross-device migration scenario is as follows: The user migrates a video playback task from a tablet to a smart TV. The video application on the tablet exits. From the perspective of application development, cross-device migration enables the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) component running on device A to migrate to and keep running on device B. After the migration is complete, the UIAbility component on device A automatically exits (depending on the setting). 6 7Cross-device migration supports the following features: 8 9- Saving and restoring custom data 10 11- Saving and restoring page routing information and page component status data 12 13- Checking application compatibility 14 15- Dynamically setting the migration state (**ACTIVE** by default) 16 17 For example, for an editing application, only the text editing page needs to be migrated to the target device. In this case, you can call [setMissionContinueState](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) for precise control. 18 19- Determining whether to restore the page stack (restored by default) 20 21 If an application wants to customize the page to be displayed after being migrated to the target device, you can use [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) for precise control. 22 23- Determining whether to exit the application on the source device after a successful migration (application exit by default) 24 25 You can use [SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) for precise control. 26 27 > **NOTE** 28 > 29 > You only need to develop an application with the migration capabilities. System applications will trigger cross-device migration. 30 31## Working Principles 32 33 34 351. On the source device, the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) uses the [onContinue()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncontinue) callback to save service data to be migrated. For example, to complete cross-device migration, a browser application uses the **onContinue()** callback to save service data such as the page URL. 362. The distributed framework provides a mechanism for saving and restoring application page stacks and service data across devices. It sends the data from the source device to the target device. 373. On the target device, the same UIAbility uses the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback (in the case of cold start) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) callback (in the case of hot start) to restore the service data. 38 39## Cross-Device Migration Process 40 41The following figure shows the cross-device migration process when a migration request is initiated from the migration entry of the peer device. 42 43 44 45## Constraints 46 47- Cross-device migration must be performed between the same [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) component. In other words, **bundleName**, **abilityName**, and **signature** of the component on the two devices must be the same. 48- For better user experience, the data to be transmitted via the **wantParam** parameter must be less than 100 KB. 49 50## How to Develop 51 521. Configure the **continuable** tag under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). 53 54 ```json 55 { 56 "module": { 57 // ... 58 "abilities": [ 59 { 60 // ... 61 "continuable": true, // Configure the UIAbility to support migration. 62 } 63 ] 64 } 65 } 66 ``` 67 68 > **NOTE** 69 > 70 > Configure the application launch type. For details, see [UIAbility Launch Type](uiability-launch-type.md). 71 722. Implement **onContinue()** in the UIAbility on the source device. 73 74 When a migration is triggered for the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md), [onContinue()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncontinue) is called on the source device. You can use either synchronous or asynchronous mode to save the data in this callback to implement application compatibility check and migration decision. 75 76 1. Saving data to migrate: You can save the data to migrate in key-value pairs in **wantParam**. 77 78 2. (Optional) Checking application compatibility: You can obtain the application version on the target device from **wantParam.version** in the **onContinue()** callback and compare it with the application version on the source device. If the version compatibility check fails, the application should notify users of the cause of the migration failure. 79 80 > **NOTE** 81 > 82 > If the compatibility issues have little or no impact on migration experience, you can skip this check. 83 84 3. Returning the migration result: You can determine whether migration is supported based on the return value of **onContinue()**. For details about the return values, see [AbilityConstant.OnContinueResult](../reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md#oncontinueresult). 85 86 87 Certain fields (listed in the table below) in **wantParam** passed in to **onContinue()** are preconfigured in the system. You can use these fields for service processing. When defining custom `wantParam` data, do not use the same keys as the preconfigured ones to prevent data exceptions due to system overwrites. 88 89 | Field|Description| 90 | ---- | ---- | 91 | version | Version the application on the target device.| 92 | targetDevice | Network ID of the target device.| 93 94 ```ts 95 import { AbilityConstant, UIAbility } from '@kit.AbilityKit'; 96 import { hilog } from '@kit.PerformanceAnalysisKit'; 97 import { promptAction } from '@kit.ArkUI'; 98 99 const TAG: string = '[MigrationAbility]'; 100 const DOMAIN_NUMBER: number = 0xFF00; 101 102 export default class MigrationAbility extends UIAbility { 103 // Prepare data to migrate in onContinue. 104 onContinue(wantParam: Record<string, Object>):AbilityConstant.OnContinueResult { 105 let targetVersion = wantParam.version; 106 let targetDevice = wantParam.targetDevice; 107 hilog.info(DOMAIN_NUMBER, TAG, `onContinue version = ${targetVersion}, targetDevice: ${targetDevice}`); 108 109 // The application can set the minimum compatible version based on the source version, which can be obtained from the versionCode field in the app.json5 file. This is to prevent incompatibility caused because the target version is too earlier. 110 let versionThreshold: number = -1; // Use the minimum version supported by the application. 111 // Compatibility verification 112 if (targetVersion < versionThreshold) { 113 // It is recommended that users be notified of the reason why the migration is rejected if the version compatibility check fails. 114 promptAction.showToast({ 115 message: 'The target application version is too early to continue. Update the application and try again.', 116 duration: 2000 117 }) 118 // Return MISMATCH when the compatibility check fails. 119 return AbilityConstant.OnContinueResult.MISMATCH; 120 } 121 122 // Save the data to migrate in the custom field (for example, data) of wantParam. 123 const continueInput = 'Data to migrate'; 124 wantParam['data'] = continueInput; 125 126 return AbilityConstant.OnContinueResult.AGREE; 127 } 128 } 129 ``` 130 1313. For the UIAbility on the target device, implement [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to restore the data and load the UI. 132 133 The APIs to call vary according to the launch types, as shown below. 134 135  136 137 > **NOTE** 138 > 139 > When an application is launched as a result of a migration, the [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore) lifecycle callback function, rather than [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate), is triggered following **onCreate()** or **onNewWant()**. This sequence occurs for both cold and hot starts. 140 > 141 > If you have performed some necessary initialization operations during application launch in **onWindowStageCreate()**, you must perform the same initialization operations in **onWindowStageRestore()** after the migration to avoid application exceptions. 142 143 - The **launchReason** parameter in the **onCreate()** or **onNewWant()** callback specifies whether the launch is triggered as a result of a migration (whether the value is **CONTINUATION**). 144 - You can obtain the saved data from the [want](../reference/apis-ability-kit/js-apis-app-ability-want.md) parameter. 145 - To use system-level page stack restoration, you must call [restoreWindowStage()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextrestorewindowstage) to trigger page restoration with page stacks before **onCreate()** or **onNewWant()** is complete. For details, see [On-Demand Page Stack Migration](./hop-cross-device-migration.md#on-demand-page-stack-migration). 146 147 ```ts 148 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 149 import { hilog } from '@kit.PerformanceAnalysisKit'; 150 151 const TAG: string = '[MigrationAbility]'; 152 const DOMAIN_NUMBER: number = 0xFF00; 153 154 export default class MigrationAbility extends UIAbility { 155 storage : LocalStorage = new LocalStorage(); 156 157 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 158 hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); 159 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 160 // Restore the saved data from want.parameters. 161 let continueInput = ''; 162 if (want.parameters !== undefined) { 163 continueInput = JSON.stringify(want.parameters.data); 164 hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); 165 } 166 // Trigger page restoration. 167 this.context.restoreWindowStage(this.storage); 168 } 169 } 170 171 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 172 hilog.info(DOMAIN_NUMBER, TAG, 'onNewWant'); 173 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 174 // Restore the saved data from want.parameters. 175 let continueInput = ''; 176 if (want.parameters !== undefined) { 177 continueInput = JSON.stringify(want.parameters.data); 178 hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); 179 } 180 // Trigger page restoration. 181 this.context.restoreWindowStage(this.storage); 182 } 183 } 184 } 185 ``` 186 187## Configuring Optional Migration Features 188 189### Dynamically Setting the Migration State 190 191Since API version 10, you can dynamically set the migration state. Specifically, you can enable or disable migration as required by calling [setMissionContinueState()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10). By default, **ACTIVE** is set for an application, indicating that migration is enabled. 192 193**Time for Setting the Migration State** 194 195To implement special scenarios, for example, where migration is required only for a specific page or upon a specific event, perform the following steps: 196 1971. In the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) lifecycle callback of the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md), disable cross-device migration. 198 199 ```ts 200 // MigrationAbility.ets 201 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 202 import { hilog } from '@kit.PerformanceAnalysisKit'; 203 204 const TAG: string = '[MigrationAbility]'; 205 const DOMAIN_NUMBER: number = 0xFF00; 206 207 export default class MigrationAbility extends UIAbility { 208 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 209 // ... 210 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { 211 hilog.info(DOMAIN_NUMBER, TAG, `setMissionContinueState INACTIVE result: ${JSON.stringify(result)}`); 212 }); 213 // ... 214 } 215 } 216 ``` 217 218 2. To enable cross-device migration for a specific page, call the migration API in [onPageShow()](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#onpageshow) of the page. 219 220 ```ts 221 // Page_MigrationAbilityFirst.ets 222 import { AbilityConstant, common } from '@kit.AbilityKit'; 223 import { hilog } from '@kit.PerformanceAnalysisKit'; 224 225 const TAG: string = '[MigrationAbility]'; 226 const DOMAIN_NUMBER: number = 0xFF00; 227 228 @Entry 229 @Component 230 struct Page_MigrationAbilityFirst { 231 private context = getContext(this) as common.UIAbilityContext; 232 build() { 233 // ... 234 } 235 // ... 236 onPageShow(){ 237 // When the page is displayed, set the migration state to ACTIVE. 238 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { 239 hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); 240 }); 241 } 242 } 243 ``` 244 2453. To enable cross-device migration for a specific event, call the migration API in the event. The following uses the [onClick()](../reference/apis-arkui/arkui-ts/ts-universal-events-click.md#onclick) event of the **Button** component as an example: 246 247 ```ts 248 // Page_MigrationAbilityFirst.ets 249 import { AbilityConstant, common } from '@kit.AbilityKit'; 250 import { hilog } from '@kit.PerformanceAnalysisKit'; 251 import { promptAction } from '@kit.ArkUI'; 252 253 const TAG: string = '[MigrationAbility]'; 254 const DOMAIN_NUMBER: number = 0xFF00; 255 256 @Entry 257 @Component 258 struct Page_MigrationAbilityFirst { 259 private context = getContext(this) as common.UIAbilityContext; 260 build() { 261 Column() { 262 //... 263 List({ initialIndex: 0 }) { 264 ListItem() { 265 Row() { 266 //... 267 } 268 .onClick(() => { 269 // When the button is clicked, set the migration state to ACTIVE. 270 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { 271 hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); 272 promptAction.showToast({ 273 message: 'Success' 274 }); 275 }); 276 }) 277 } 278 //... 279 } 280 //... 281 } 282 //... 283 } 284 } 285 ``` 286 287### Migrating the Page Stack on Demand 288 289 290> **NOTE** 291> 292> Currently, only the page stack implemented based on the router module can be automatically restored. The page stack implemented using the **Navigation** component cannot be automatically restored. 293> If an application uses the **Navigation** component for routing, you can disable default page stack migration by setting [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) to **false**. In addition, save the page (or page stack) to be migrated in **want**, and manually load the specified page on the target device. 294 295By default, the page stack is restored during the migration of a [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md). Before [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) finishes the execution, call [restoreWindowStage()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#restore) to pass in the current window context, which will be used for page stack loading and restoration. The **restoreWindowStage()** API must be executed in a synchronous API. If it is executed during an asynchronous callback, there is a possibility that the page fails to be loaded during application startup. 296 297The following uses **onCreate()** as an example: 298 299```ts 300import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 301 302export default class MigrationAbility extends UIAbility { 303 storage : LocalStorage = new LocalStorage(); 304 305 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 306 // ... 307 // Trigger page restoration before the synchronous API finishes the execution. 308 this.context.restoreWindowStage(this.storage); 309 } 310} 311``` 312 313If the application does not want to use the page stack restored by the system, set [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) to **false**, and specify the page to be displayed after the migration in [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore). If the page to be displayed after the migration is not specified, a blank page will be displayed. 314 315For example, a UIAbility does not want to restore the page stack displayed on the source device. Instead, it wants **Page_MigrationAbilityThird** to be restored after the migration. 316 317```ts 318// MigrationAbility.ets 319import { AbilityConstant, UIAbility, wantConstant } from '@kit.AbilityKit'; 320import { hilog } from '@kit.PerformanceAnalysisKit'; 321import { window } from '@kit.ArkUI'; 322 323const TAG: string = '[MigrationAbility]'; 324const DOMAIN_NUMBER: number = 0xFF00; 325 326export default class MigrationAbility extends UIAbility { 327 onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { 328 // ... 329 // Configure not to use the system page stack during restoration. 330 wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; 331 return AbilityConstant.OnContinueResult.AGREE; 332 } 333 334 onWindowStageRestore(windowStage: window.WindowStage): void { 335 // If the system page stack is not used for restoration, specify the page to be displayed after the migration. 336 windowStage.loadContent('pages/page_migrationability/Page_MigrationAbilityThird', (err, data) => { 337 if (err.code) { 338 hilog.error(DOMAIN_NUMBER, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 339 return; 340 } 341 }); 342 } 343} 344``` 345 346### Exiting the Application on Demand 347 348By default, the application on the source device exits after the migration is complete. If you want the application to continue running on the source device after the migration or perform other operations (such as saving drafts and clearing resources) before exiting on the source device, you can set [SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) to **false**. 349 350Example: A UIAbility on the source device does not exit after a successful migration. 351 352```ts 353import { AbilityConstant, UIAbility, wantConstant } from '@kit.AbilityKit'; 354import { hilog } from '@kit.PerformanceAnalysisKit'; 355 356const TAG: string = '[MigrationAbility]'; 357const DOMAIN_NUMBER: number = 0xFF00; 358 359export default class MigrationAbility extends UIAbility { 360 // ... 361 onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { 362 hilog.info(DOMAIN_NUMBER, TAG, `onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); 363 wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; 364 return AbilityConstant.OnContinueResult.AGREE; 365 } 366} 367``` 368 369### Supporting Cross-Device Migration Between Different Abilities in the Same Application 370Generally, the same ability is involved during a cross-device migration. However, different ability names may be configured for the same service on different device types, resulting in different abilities. To support migration in this scenario, you can configure the **continueType** flag under **abilities** in the [module.json5](../quick-start/module-configuration-file.md) file for association. 371 372The values of the **continueType** tag of the two abilities must be the same. The following is an example: 373 > **NOTE** 374 > 375 > The value of **continueType** must be unique in an application. The value is a string of a maximum of 127 bytes consisting of letters, digits, and underscores (_). 376 > The **continueType** tag is a string array. If multiple fields are configured, only the first field takes effect. 377 378```json 379 // Device A 380 { 381 "module": { 382 // ... 383 "abilities": [ 384 { 385 // ... 386 "name": "Ability-deviceA", 387 "continueType": ['continueType1'], // Configuration of the continueType tag. 388 } 389 ] 390 } 391 } 392 393 // Device B 394 { 395 "module": { 396 // ... 397 "abilities": [ 398 { 399 // ... 400 "name": "Ability-deviceB", 401 "continueType": ['continueType1'], // Same as the value of continueType on device A. 402 } 403 ] 404 } 405 } 406``` 407 408### Quickly Starting a Target Application 409By default, the target application on the peer device is not started immediately when the migration is initiated. It waits until the data to migrate is synchronized from the source device to the peer device. To start the target application immediately upon the initiation of a migration, you can add the **_ContinueQuickStart** suffix to the value of **continueType**. In this way, only the migrated data is restored after the data synchronization, delivering an even better migration experience. 410 411 ```json 412 { 413 "module": { 414 // ... 415 "abilities": [ 416 { 417 // ... 418 "name": "EntryAbility" 419 "continueType": ['EntryAbility_ContinueQuickStart'], // If the continueType tag is configured, add the suffix '_ContinueQuickStart' to its value. If the continueType tag is not configured, you can use AbilityName + '_ContinueQuickStart' as the value of continueType to implement quick startup of the target application. 420 } 421 ] 422 } 423 } 424 ``` 425With quick start, the target application starts while waiting for the data to migration, minimizing the duration that users wait for the migration to complete. Note that, for the first migration with quick start enabled, the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) callback is triggered, in which **launchReason** is **PREPARE_CONTINUATION**. The introduce of the **launchReason** parameter solves problems related to redirection and timing. It also provides a loading screen during quick startup, delivering a better experience. The following figure shows the quick start process. 426 427 428 429For an application configured with quick startup, two start requests are received for a migration. The differences are as follows: 430 431| Scenario | Lifecycle Function | launchParam.launchReason | 432| -------------- | ------------------------------------------- | ------------------------------------------------- | 433| First start request| onCreate (in the case of cold start)<br>or onNewWant (in the case of hot start)| AbilityConstant.LaunchReason.PREPARE_CONTINUATION | 434| Second start request| onNewWant | AbilityConstant.LaunchReason.CONTINUATION | 435 436If fast start is not configured, only one start request is received. 437 438| Scenario | Lifecycle Function | launchParam.launchReason | 439| ------------ | ------------------------------------------- | ----------------------------------------- | 440| One start request| onCreate (in the case of cold start)<br>or onNewWant (in the case of hot start)| AbilityConstant.LaunchReason.CONTINUATION | 441 442When quick start is configured, you also need to implement [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). The following is an example: 443 444```ts 445import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 446import { hilog } from '@kit.PerformanceAnalysisKit'; 447 448const TAG: string = '[MigrationAbility]'; 449const DOMAIN_NUMBER: number = 0xFF00; 450 451export default class MigrationAbility extends UIAbility { 452 storage : LocalStorage = new LocalStorage(); 453 454 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 455 hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); 456 457 // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. 458 if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { 459 // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). 460 // Handle issues related to custom redirection and timing. 461 // ... 462 } 463 } 464 465 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 466 hilog.info(DOMAIN_NUMBER, TAG, 'onNewWant'); 467 468 // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. 469 if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { 470 // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). 471 // Handle issues related to custom redirection and timing. 472 // ... 473 } 474 475 // 2. Trigger the lifecycle callback when the migration data is restored. 476 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 477 // Restore the saved data from want.parameters. 478 let continueInput = ''; 479 if (want.parameters !== undefined) { 480 continueInput = JSON.stringify(want.parameters.data); 481 hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); 482 } 483 // Trigger page restoration. 484 this.context.restoreWindowStage(this.storage); 485 } 486 } 487} 488``` 489 490When the target application is quickly started, the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) and [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore) callbacks are triggered in sequence. Generally, in **onWindowStageCreate()**, you call [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to load the page. This API throws an asynchronous task to load the home page. This asynchronous task is not synchronous with **onWindowStageRestore()**. If UI-related APIs (such as route APIs) are used in **onWindowStageRestore()**, the invoking time may be earlier than the home page loading time. To ensure the normal loading sequence, you can use [setTimeout()](../reference/common/js-apis-timer.md#settimeout) to throw an asynchronous task for related operations. For details, see the sample code. 491 492The sample code is as follows: 493 494```ts 495import { UIAbility } from '@kit.AbilityKit'; 496import { hilog } from '@kit.PerformanceAnalysisKit'; 497import { UIContext, window } from '@kit.ArkUI'; 498 499export default class EntryAbility extends UIAbility { 500 private uiContext: UIContext | undefined = undefined; 501 502 // ... 503 504 onWindowStageCreate(windowStage: window.WindowStage): void { 505 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 506 507 windowStage.loadContent('pages/Index', (err) => { 508 if (err.code) { 509 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 510 return; 511 } 512 this.uiContext = windowStage.getMainWindowSync().getUIContext(); 513 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); 514 }); 515 } 516 517 onWindowStageRestore(windowStage: window.WindowStage): void { 518 setTimeout(() => { 519 // Throw the asynchronous task execution route to ensure that the task is executed after the home page is loaded. 520 this.uiContext?.getRouter().pushUrl({ 521 url: 'pages/examplePage' 522 }); 523 }, 0); 524 } 525 526 // ... 527} 528``` 529 530## Cross-Device Data Migration 531 532Two data migration modes are provided. You can select either of them as required. 533 > **NOTE** 534 > 535 > Through the configuration of **restoreId**, certain ArkUI components can be restored to a given state on the target device after migration. For details, see [restoreId](../../application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-restoreId.md). 536 > 537 > If distributed data objects need to be migrated, you must perform the following operations (required only in API version 11 and earlier versions): 538 > 539 > 1. Declare the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 540 > 541 > 2. Display a dialog box to ask for authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/AccessToken/request-user-authorization.md). 542 543### Using wantParam for Data Migration 544 545If the size of the data to migrate is less than 100 KB, you can add fields to **wantParam** to migrate the data. An example is as follows: 546 547```ts 548import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 549import { hilog } from '@kit.PerformanceAnalysisKit'; 550 551const TAG: string = '[MigrationAbility]'; 552const DOMAIN_NUMBER: number = 0xFF00; 553 554export default class MigrationAbility extends UIAbility { 555 storage: LocalStorage = new LocalStorage(); 556 557 // Save the data on the source device. 558 onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { 559 // Save the data to migrate in the custom field (for example, data) of wantParam. 560 const continueInput = 'Data to migrate'; 561 wantParam['data'] = continueInput; 562 return AbilityConstant.OnContinueResult.AGREE; 563 } 564 565 // Restore the data on the target device. 566 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 567 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 568 // Obtain the data saved. 569 let continueInput = ''; 570 if (want.parameters !== undefined) { 571 continueInput = JSON.stringify(want.parameters.data); 572 hilog.info(DOMAIN_NUMBER, TAG, `continue input ${continueInput}`); 573 } 574 // Trigger page restoration. 575 this.context.restoreWindowStage(this.storage); 576 } 577 } 578 579 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 580 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 581 let continueInput = ''; 582 if (want.parameters !== undefined) { 583 continueInput = JSON.stringify(want.parameters.data); 584 hilog.info(DOMAIN_NUMBER, TAG, `continue input ${JSON.stringify(continueInput)}`); 585 } 586 // Trigger page restoration. 587 this.context.restoreWindowStage(this.storage); 588 } 589 } 590} 591``` 592 593### Using Distributed Data Objects for Data Migration 594 595If the size of the data to migrate is greater than 100 KB or a file needs to be migrated, you can use a [distributed data object](../reference/apis-arkdata/js-apis-data-distributedobject.md) to implement data migration. For details, see [Cross-Device Synchronization of Distributed Data Objects](../database/data-sync-of-distributed-data-object.md). 596 597 > **NOTE** 598 > 599 > Since API version 12, it is difficult to obtain the file synchronization completion time when [cross-device file access](../file-management/file-access-across-devices.md) is used to migrate a file. To ensure a higher success rate, you are advised to use distributed data objects to carry assets. File migration implemented through cross-device file access still takes effect. 600 601#### Basic Data Migration 602 603To use a distributed data object, you must save data in the [onContinue()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncontinue) API on the source device and restore data in the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) API of the target device. 604 605On the source device, save the data to migrate to a distributed [data object](../reference/apis-arkdata/js-apis-data-distributedobject.md#dataobject). 606 607- Use [create()](../reference/apis-arkdata/js-apis-data-distributedobject.md#distributeddataobjectcreate9) in **onContinue()** to create a distributed data object and add the data to migrate to the object. 608- Use [genSessionId()](../reference/apis-arkdata/js-apis-data-distributedobject.md#distributeddataobjectgensessionid) to generate a data object network ID, use the ID to call [setSessionId()](../reference/apis-arkdata/js-apis-data-distributedobject.md#setsessionid9) to add the data object to the network, and activate the distributed data object. 609- Use [save()](../reference/apis-arkdata/js-apis-data-distributedobject.md#save9) to persist the activated distributed data object to ensure that the peer device can still obtain data after the application exits from the source device. 610- The generated session ID is transferred to the peer device through **want** for activation and synchronization purposes. 611 612> **NOTE** 613> 614> Distributed data objects must be activated before being made persistent. Therefore, the **save()** API must be called after setSessionId(). 615> For applications that need to exit from the source device after migration, use **await** to wait until the **save()** API finishes execution. This prevents the application from exiting before data is saved. Since API version 12, an asynchronous **onContinue()** API is provided for this scenario. 616> Currently, the **sessionId** field in **wantParams** is occupied by the system in the migration process. You are advised to define another key in **wantParams** to store the ID to avoid data exceptions. 617 618The sample code is as follows: 619 620```ts 621// Import the modules. 622import { distributedDataObject } from '@kit.ArkData'; 623import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 624import { BusinessError } from '@kit.BasicServicesKit'; 625import { hilog } from '@kit.PerformanceAnalysisKit'; 626 627const TAG: string = '[MigrationAbility]'; 628const DOMAIN_NUMBER: number = 0xFF00; 629 630// Define service data. 631class ParentObject { 632 mother: string 633 father: string 634 635 constructor(mother: string, father: string) { 636 this.mother = mother 637 this.father = father 638 } 639} 640 641// Strings, digits, Boolean values, and objects can be transferred. 642class SourceObject { 643 name: string | undefined 644 age: number | undefined 645 isVis: boolean | undefined 646 parent: ParentObject | undefined 647 648 constructor(name: string | undefined, age: number | undefined, isVis: boolean | undefined, parent: ParentObject | undefined) { 649 this.name = name 650 this.age = age 651 this.isVis = isVis 652 this.parent = parent 653 } 654} 655 656export default class MigrationAbility extends UIAbility { 657 d_object?: distributedDataObject.DataObject; 658 659 async onContinue(wantParam: Record<string, Object>): Promise<AbilityConstant.OnContinueResult> { 660 // ... 661 let parentSource: ParentObject = new ParentObject('jack mom', 'jack Dad'); 662 let source: SourceObject = new SourceObject("jack", 18, false, parentSource); 663 664 // Create a distributed data object. 665 this.d_object = distributedDataObject.create(this.context, source); 666 667 // Generate a data object network ID and activate the distributed data object. 668 let dataSessionId: string = distributedDataObject.genSessionId(); 669 this.d_object.setSessionId(dataSessionId); 670 671 // Transfer the network ID to the peer device. 672 wantParam['dataSessionId'] = dataSessionId; 673 674 // Persist the data object to ensure that the peer device can restore the data object even if the application exits after the migration. 675 // Obtain the network ID of the peer device from wantParam.targetDevice as an input parameter. 676 await this.d_object.save(wantParam.targetDevice as string).then((result: 677 distributedDataObject.SaveSuccessResponse) => { 678 hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in saving. SessionId: ${result.sessionId}`, 679 `version:${result.version}, deviceId:${result.deviceId}`); 680 }).catch((err: BusinessError) => { 681 hilog.error(DOMAIN_NUMBER, TAG, 'Failed to save. Error: ', JSON.stringify(err) ?? ''); 682 }); 683 684 return AbilityConstant.OnContinueResult.AGREE; 685 } 686} 687``` 688 689In [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant), the peer device adds the same distributed data object as the source device for networking, in order to restore data. 690 691- Create an empty distributed data object to receive restored data. 692- Read the network ID of the distributed data object from [want](../reference/apis-ability-kit/js-apis-app-ability-want.md). 693- Register [on()](../reference/apis-arkdata/js-apis-data-distributedobject.md#onstatus9) to listen for data changes. In the event callback indicating that **status** is **restore**, implement the service operations that need to be performed when the data restoration is complete. 694- Call [setSessionId()](../reference/apis-arkdata/js-apis-data-distributedobject.md#setsessionid9) to add the data object to the network, and activate the distributed data object. 695 696> **NOTE** 697> 698> 1. The distributed data object of the peer device to be added to the network cannot be a temporary variable. This is because the callback of the **on()** API may be executed after **onCreate()** or **onNewWant()** finishes execution. If the temporary variable is released, a null pointer exception may occur. You can use a class member variable to avoid this problem. 699> 2. The attributes of the object used to create the distributed data object on the peer device must be undefined before the distributed data object is activated. Otherwise, the source data will be overwritten after new data is added to the network, and data restoration will fail. 700> 3. Before activating the distributed data object, call **on()** to listen for the restore event. This helps prevent data restoration failure caused by event missing. 701 702The sample code is as follows: 703 704```ts 705import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 706import { distributedDataObject } from '@kit.ArkData'; 707import { hilog } from '@kit.PerformanceAnalysisKit'; 708 709const TAG: string = '[MigrationAbility]'; 710const DOMAIN_NUMBER: number = 0xFF00; 711 712// The definition of the example data object is the same as above. 713export default class MigrationAbility extends UIAbility { 714 d_object?: distributedDataObject.DataObject; 715 716 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 717 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 718 // ... 719 // Call the encapsulated distributed data object processing function. 720 this.handleDistributedData(want); 721 } 722 } 723 724 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 725 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 726 if (want.parameters !== undefined) { 727 // ... 728 // Call the encapsulated distributed data object processing function. 729 this.handleDistributedData(want); 730 } 731 } 732 } 733 734 handleDistributedData(want: Want) { 735 // Create an empty distributed data object. 736 let remoteSource: SourceObject = new SourceObject(undefined, undefined, undefined, undefined); 737 this.d_object = distributedDataObject.create(this.context, remoteSource); 738 739 // Read the network ID of the distributed data object. 740 let dataSessionId = ''; 741 if (want.parameters !== undefined) { 742 dataSessionId = want.parameters.dataSessionId as string; 743 } 744 745 // Add a data change listener. 746 this.d_object.on("status", (sessionId: string, networkId: string, status: 'online' | 'offline' | 'restored') => { 747 hilog.info(DOMAIN_NUMBER, TAG, "status changed " + sessionId + " " + status + " " + networkId); 748 if (status == 'restored') { 749 if (this.d_object) { 750 // Read data from the distributed data object when the restore status is received. 751 hilog.info(DOMAIN_NUMBER, TAG, "restored name:" + this.d_object['name']); 752 hilog.info(DOMAIN_NUMBER, TAG, "restored parents:" + JSON.stringify(this.d_object['parent'])); 753 } 754 } 755 }); 756 757 // Activate the distributed data object. 758 this.d_object.setSessionId(dataSessionId); 759 } 760} 761``` 762 763#### File Migration 764 765A file, such as an image or document, must be converted to the [commonType.Asset](../reference/apis-arkdata/js-apis-data-commonType.md#asset) type before being encapsulated into a distributed data objects for migration. The migration implementation is similar to that of a common distributed data object. The following describes only the differences. 766 767On the source device, save the file asset to migrate to a distributed [data object](../reference/apis-arkdata/js-apis-data-distributedobject.md#dataobject). 768 769- Copy the file asset to the [distributed file directory](application-context-stage.md#obtaining-application-file-paths). For details about related APIs and usage, see [basic file APIs](../file-management/app-file-access.md). 770- Use the file in the distributed file directory to create an asset object. 771- Save the asset object as the root attribute of the distributed data object. 772 773Then, add the data object to the network and persist it. The procedure is the same as the migration of a common data object on the source device. 774 775An example is as follows: 776 777```ts 778// Import the modules. 779import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 780import { distributedDataObject, commonType } from '@kit.ArkData'; 781import { fileIo, fileUri } from '@kit.CoreFileKit'; 782import { hilog } from '@kit.PerformanceAnalysisKit'; 783import { BusinessError } from '@ohos.base'; 784 785const TAG: string = '[MigrationAbility]'; 786const DOMAIN_NUMBER: number = 0xFF00; 787 788// Define a data object. 789class ParentObject { 790 mother: string 791 father: string 792 793 constructor(mother: string, father: string) { 794 this.mother = mother 795 this.father = father 796 } 797} 798 799class SourceObject { 800 name: string | undefined 801 age: number | undefined 802 isVis: boolean | undefined 803 parent: ParentObject | undefined 804 attachment: commonType.Asset | undefined // New asset attribute. 805 806 constructor(name: string | undefined, age: number | undefined, isVis: boolean | undefined, 807 parent: ParentObject | undefined, attachment: commonType.Asset | undefined) { 808 this.name = name 809 this.age = age 810 this.isVis = isVis 811 this.parent = parent 812 this.attachment = attachment; 813 } 814} 815 816export default class MigrationAbility extends UIAbility { 817 d_object?: distributedDataObject.DataObject; 818 819 async onContinue(wantParam: Record<string, Object>): Promise<AbilityConstant.OnContinueResult> { 820 // ... 821 822 // 1. Write the asset to the distributed file directory. 823 let distributedDir: string = this.context.distributedFilesDir; // Obtain the distributed file directory. 824 let fileName: string = '/test.txt'; // File name. 825 let filePath: string = distributedDir + fileName; // File path. 826 827 try { 828 // Create a file in the distributed directory. 829 let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); 830 hilog.info(DOMAIN_NUMBER, TAG, 'Create file success.'); 831 // Write content to the file. (If the asset is an image, convert the image into a buffer and write the buffer.) 832 fileIo.writeSync(file.fd, '[Sample] Insert file content here.'); 833 // Close the file. 834 fileIo.closeSync(file.fd); 835 } catch (error) { 836 let err: BusinessError = error as BusinessError; 837 hilog.error(DOMAIN_NUMBER, TAG, `Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`); 838 } 839 840 // 2. Use the file in the distributed file directory to create an asset object. 841 let distributedUri: string = fileUri.getUriFromPath(filePath); // Obtain the URI of the distributed file. 842 843 // Obtain file parameters. 844 let ctime: string = ''; 845 let mtime: string = ''; 846 let size: string = ''; 847 await fileIo.stat(filePath).then((stat: fileIo.Stat) => { 848 ctime = stat.ctime.toString(); // Creation time 849 mtime = stat.mtime.toString(); // Modification time 850 size = stat.size.toString(); // File size 851 }) 852 853 // Create an asset object. 854 let attachment: commonType.Asset = { 855 name: fileName, 856 uri: distributedUri, 857 path: filePath, 858 createTime: ctime, 859 modifyTime: mtime, 860 size: size, 861 } 862 863 // 3. Use the asset object as the root attribute of the distributed data object to create a distributed data object. 864 let parentSource: ParentObject = new ParentObject('jack mom', 'jack Dad'); 865 let source: SourceObject = new SourceObject("jack", 18, false, parentSource, attachment); 866 this.d_object = distributedDataObject.create(this.context, source); 867 868 // Generate a network ID, activate the distributed data object, and save the data persistently. 869 // ... 870 871 return AbilityConstant.OnContinueResult.AGREE; 872 } 873} 874``` 875 876The target application must create an asset object whose attributes are empty as the root attribute of the distributed data object. When the [on()](../reference/apis-arkdata/js-apis-data-distributedobject.md#onstatus9) event callback in which **status** is **restored** is received, the data synchronization including the asset is complete. The asset object of source application can be obtained in the same way as the basic data. 877 878> **NOTE** 879> 880> When the target application creates the distributed data object, the assets in the **SourceObject** object cannot be directly initialized using **undefined**. You need to create an asset object whose initial values of all attributes are empty so that the distributed object can identify the asset type. 881 882```ts 883import { UIAbility, Want } from '@kit.AbilityKit'; 884import { distributedDataObject, commonType } from '@kit.ArkData'; 885import { hilog } from '@kit.PerformanceAnalysisKit'; 886 887const TAG: string = '[MigrationAbility]'; 888const DOMAIN_NUMBER: number = 0xFF00; 889 890export default class MigrationAbility extends UIAbility { 891 d_object?: distributedDataObject.DataObject; 892 893 handleDistributedData(want: Want) { 894 // ... 895 // Create an asset object whose attributes are empty. 896 let attachment: commonType.Asset = { 897 name: '', 898 uri: '', 899 path: '', 900 createTime: '', 901 modifyTime: '', 902 size: '', 903 } 904 905 // Use the empty asset object to create a distributed data object. Other basic attributes can be directly set to undefined. 906 let source: SourceObject = new SourceObject(undefined, undefined, undefined, undefined, attachment); 907 this.d_object = distributedDataObject.create(this.context, source); 908 909 this.d_object.on("status", (sessionId: string, networkId: string, status: 'online' | 'offline' | 'restored') => { 910 if (status == 'restored') { 911 if (this.d_object) { 912 // The restored event callback is received, indicating that the synchronization of the distributed asset object is complete. 913 hilog.info(DOMAIN_NUMBER, TAG, "restored attachment:" + JSON.stringify(this.d_object['attachment'])); 914 } 915 } 916 }); 917 // ... 918 } 919} 920``` 921 922If you want to synchronize multiple assets, use either of the following methods: 923 924- Method 1: Implement each asset as a root attribute of the distributed data object. This applies to scenarios where the number of assets to migrate is fixed. 925- Method 2: Transfer the asset array as an object. This applies to scenarios where the number of assets to migrate changes dynamically (for example, a user selects a variable number of images). Currently, the asset array cannot be directly transferred as the root attribute. 926 927To implement method 1, you can add more assets by referring to the method of adding an asset. To implement method 2, refer to the code snippet below: 928 929```ts 930// Import the modules. 931import { distributedDataObject, commonType } from '@kit.ArkData'; 932import { UIAbility } from '@kit.AbilityKit'; 933 934// Define a data object. 935class SourceObject { 936 name: string | undefined 937 assets: Object | undefined // Add an object attribute to the distributed data object. 938 939 constructor(name: string | undefined, assets: Object | undefined) { 940 this.name = name 941 this.assets = assets; 942 } 943} 944 945export default class MigrationAbility extends UIAbility { 946 d_object?: distributedDataObject.DataObject; 947 948 // This API is used to convert an asset array into a record. 949 GetAssetsWapper(assets: commonType.Assets): Record<string, commonType.Asset> { 950 let wrapper: Record<string, commonType.Asset> = {} 951 let num: number = assets.length; 952 for (let i: number = 0; i < num; i++) { 953 wrapper[`asset${i}`] = assets[i]; 954 } 955 return wrapper; 956 } 957 958 async onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult { 959 // ... 960 961 // Create multiple asset objects. 962 let attachment1: commonType.Asset = { 963 // ... 964 } 965 966 let attachment2: commonType.Asset = { 967 // ... 968 } 969 970 // Insert the asset objects into the asset array. 971 let assets: commonType.Assets = []; 972 assets.push(attachment1); 973 assets.push(attachment2); 974 975 // Convert the asset array into a record object and use it to create a distributed data object. 976 let assetsWrapper: Object = this.GetAssetsWapper(assets); 977 let source: SourceObject = new SourceObject("jack", assetsWrapper); 978 this.d_object = distributedDataObject.create(this.context, source); 979 980 // ... 981 } 982} 983``` 984 985## Verification Guide 986 987A mission center demo is provided for you to verify the migration capability of your application. The following walks you through on how to verify migration by using the demo. 988 989> **NOTE** 990> 991> The screenshots in this section are for reference only. The DevEco Studio and SDK versions in use prevail. 992 993**Compiling and Installing the Demo** 994 9951. [Switch to the full SDK](../faqs/full-sdk-switch-guide.md) to compile and install the mission center. 996 9972. Download the sample code of the [mission center demo](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/missionCenterDemo/dmsDemo/entry/src/main). 998 9993. Build the project file. 1000 1001 1. Create an empty project and replace the corresponding folders with the downloaded files. 1002 1003  1004 1005 2. Complete the signature, build, and installation. 1006 The default signature permission provided by the automatic signature template of DevEco Studio is normal. The mission center demo requires the **ohos.permission.MANAGE_MISSIONS** permission, which is at the system_core level. Therefore, you must escalate the permission to the system_core level. 1007 1. Change **"apl":"normal"** to **"apl":"system_core"** in the **UnsignedReleasedProfileTemplate.json** file in **openharmony\apiVersion\toolchains\lib**, where apiVersion is a digit, for example, **10**. 1008 1009 2. Choose **File > Project Structure**. 1010 1011  1012 1013 3. Click **Signing Configs** and click **OK**. 1014 1015  1016 1017 4. Connect to the developer board and run the demo. 1018 1019**Device Networking** 1020 10211. Open the calculators of devices A and B. 10222. Click the arrow in the upper right corner to select device B. 10233. Select a trusted device on device B. The PIN is displayed. 10244. Enter the PIN on device A. 10255. Verify the networking. Enter a number on device A. If the number is displayed on device B, the networking is successful. 1026 1027**Initiation Migration** 1028 10291. Open your application on device B, and open the mission center demo on device A. The name of device A and the name of device B are displayed on the mission center demo. 10302. Touch the name of device B. The application card list of device B is displayed. 10313. Drag the application card to be connected to the name of device A. The application on device A is started. 1032 1033## FAQs 1034 1035### Q1: What Can I Do If the Application Cannot Be Migrated Back to the Source Device? 1036 1037The migration state is set at the ability level. The application on the target device may have executed the command to set its own migration state (for example, set the state to **INACTIVE** in [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) during cold start or to **INACTIVE** during hot start since the application has opened a page that cannot be migrated). To ensure a migration back to the source device, you must set the migration state to **ACTIVE** in onCreate() or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). 1038 1039```ts 1040// MigrationAbility.ets 1041import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 1042import { hilog } from '@kit.PerformanceAnalysisKit'; 1043 1044const TAG: string = '[MigrationAbility]'; 1045const DOMAIN_NUMBER: number = 0xFF00; 1046 1047export default class MigrationAbility extends UIAbility { 1048 // ... 1049 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 1050 // ... 1051 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 1052 // ... 1053 // Set the migration state to ACTIVE when the launch is caused by migration. This setting copes with cold start. 1054 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { 1055 hilog.info(DOMAIN_NUMBER, TAG, `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); 1056 }); 1057 } 1058 // ... 1059 } 1060 1061 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 1062 // ... 1063 // Set the migration state to ACTIVE when the launch is caused by migration. This setting copes with hot start. 1064 if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) { 1065 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { 1066 hilog.info(DOMAIN_NUMBER, TAG, `setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); 1067 }); 1068 } 1069 } 1070 // ... 1071} 1072``` 1073 1074### Q2: What Can I Do If the Call of loadContent() Does Not Take Effect in onWindowStageRestore()? 1075 1076If page stack migration is not disabled for an application, the system migrates and loads the page stack of the application by default. In this case, if you use [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to trigger the loading of a specific page in the [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore) lifecycle callback function, the loading does not take effect and the page in the page stack is still restored. 1077 1078