目录

App Continuation for Data Migration

Overview

For app continuation, you need to select a proper data migration solution. Selecting a migration solution is directly related to data volume and whether file migration is involved, as described in the following table.

  

< 100 KB

> 100 KB

File migration is required

Migrating File Assets

Migrating File Assets

File migration is not required

Using want.param for Data Migration

Basic Data Migration

How to Implement

For details about the implementation principles, see Working Principles.

How to Develop

To implement app continuation, you need to enable the app continuation capability, configure the app launch type, save migration data on the source device, and restore data on the target device. For details about the development process, see App Continuation Overview. This topic only describes how to select a data migration solution in different scenarios.

Using want.param for Data Migration

  1. Save migration data on the source device.
    export default class EntryAbility extends UIAbility {
      // ...
      async onContinue(wantParam: Record<string, Object | undefined>): Promise<AbilityConstant.OnContinueResult> {
        // ...
        // Migrate simple data using wantParam.param
        wantParam.wantBasicData = AppStorage.get('wantBasicData');
        // ...
        // Return AGREE to allow cross-device migration
        return AbilityConstant.OnContinueResult.AGREE;
      }
      // ...
    }
  2. Restore data on the target device.
    export default class EntryAbility extends UIAbility {
      private distributedObject: distributedDataObject.DataObject | undefined = undefined;
      private storage: LocalStorage = new LocalStorage();
      private distributedFileUtil: DistributedFileUtil | undefined = undefined;
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, FORMAT, `Ability onCreate`);
        this.distributedFileUtil = new DistributedFileUtil(this.context);
        this.appContinuity(want, launchParam);
      }
    
      onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, FORMAT, `Ability onNewWant`);
        this.appContinuity(want, launchParam);
      }
    
      appContinuity(want: Want, launchParam: AbilityConstant.LaunchParam) {
        if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
          if (want.parameters !== undefined) {
            // Use want.param to migrate the simple data page data
            AppStorage.setOrCreate('wantBasicData', want.parameters.wantBasicData);
          }
          // ...
          try {
            // Restore window stage with new LocalStorage instance
            this.context.restoreWindowStage(this.storage);
          } catch (err) {
            hilog.error(DOMAIN, TAG, FORMAT, `RestoreWindowStage failed. Cause : ${err}`);
          }
        }
      }
    
      // ...
    }

Using Distributed Data Objects for Data Migration

[h2]Basic Data Migration

  1. Save migration data on the source device.

    Create a distributed data object in onContinue() of the source UIAbility and save the data. The execution process is as follows:

    1. Call create() in onContinue() to create a distributed data object and fill the data to be migrated into the distributed data object.
    2. Call genSessionId() to generate a networking ID for the distributed data object. The distributed data object calls setSessionId() to pass the ID to activate the distributed data object.
    3. Call save() to persist the activated distributed data object. This ensures that the app on the target device can continue to access the data even if the app on the source device exits.
    4. Pass the generated sessionId to the target app through want. The sessionId is used to activate the distributed data object of the target app and transfer data to the target app.
    • The distributed data object needs to be activated and then persisted. Therefore, save() must be called after setSessionId() is called.
    • To prevent the app on the source device from exiting before the data migrated to the target device is saved, use await to wait until save() is complete. Starting from API version 12, an asynchronous onContinue() API is provided for this scenario.
    • Currently, the sessionId field in wantParams is used by the system during migration. You are advised to define other key values in wantParams to store the session ID generated for the distributed data object to avoid exceptions.
    export class ContinuationData {
      public basicDataStr: string | undefined;
      public basicDataNum: number | undefined;
      public distributedData: DistributedData | undefined;
      // ...
      constructor(
        basicDataStr: string | undefined,
        basicDataNum: number | undefined,
        distributedData: DistributedData | undefined,
        // ...
      ) {
        this.basicDataStr = basicDataStr;
        this.basicDataNum = basicDataNum;
        this.distributedData = distributedData;
        // ...
      }
      // ...
    }
    export default class EntryAbility extends UIAbility {
      private distributedObject: distributedDataObject.DataObject | undefined = undefined;
      private storage: LocalStorage = new LocalStorage();
      private distributedFileUtil: DistributedFileUtil | undefined = undefined;
      // ...
      async onContinue(wantParam: Record<string, Object | undefined>): Promise<AbilityConstant.OnContinueResult> {
        if (!this.distributedFileUtil) {
          return AbilityConstant.OnContinueResult.REJECT;
        }
        // ...
        let sessionId: string = distributedDataObject.genSessionId();
        wantParam.distributedSessionId = sessionId;
        // ...
        let contentInfo: ContinuationData = new ContinuationData(
          AppStorage.get('basicDataStr') ?? '',
          AppStorage.get('basicDataNum') ?? undefined,
          AppStorage.get('distributedData') ?? undefined,
          // ...
          (AppStorage.get('pageInfos') as NavPathStack).getAllPathName()[0]
        );
        let source = await contentInfo.flatAssets();
        this.distributedObject = distributedDataObject.create(this.context, source);
        this.distributedObject.setSessionId(sessionId).catch((err: BusinessError) => {
          hilog.info(DOMAIN, TAG, FORMAT, `SetSessionId failed. Cause code: ${err.code}`);
        });
        await this.distributedObject.save(wantParam.targetDevice as string).catch((err: BusinessError) => {
          hilog.info(DOMAIN, TAG, FORMAT, `Failed to save. Code: ${err.code}`);
        });
        // Return AGREE to allow cross-device migration
        return AbilityConstant.OnContinueResult.AGREE;
      }
      // ...
    }
  2. Restore data on the target device.

    In onCreate() or onNewWant() of the target UIAbility, add the same networking ID to the distributed data object on the target device to restore data. The process is as follows:

    1. Create an empty distributed data object for receiving data to be restored.
    2. Read the networking ID of the distributed data object from want.
    3. Register on() to listen for data changes of the distributed data object. In the callback of the event whose status is restored, implement the operation to be performed when the data restoration is complete.
    4. Call setSessionId() to connect the target app to the network and activate the distributed data object.
    • The distributed data object of the target app connected to the network cannot be a temporary variable. Since on() for the distributed data object uses an asynchronous callback and may be executed after onCreate() or onNewWant() is complete. The temporary variable will be released, which causes a null pointer exception. You can use class member variables to avoid this exception.
    • Before a distributed data object on the target device is activated, set the attribute of the object used to create the distributed data object to undefined. Otherwise, the data on the source device will be overwritten by new data after the distributed data object is connected to the network, and data restore will fail.
    • Before activating a distributed data object, call on() of the object to register listening to prevent data restore failure caused by missing the restored event.
    export default class EntryAbility extends UIAbility {
      private distributedObject: distributedDataObject.DataObject | undefined = undefined;
      private storage: LocalStorage = new LocalStorage();
      private distributedFileUtil: DistributedFileUtil | undefined = undefined;
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, FORMAT, `Ability onCreate`);
        this.distributedFileUtil = new DistributedFileUtil(this.context);
        this.appContinuity(want, launchParam);
      }
    
      onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, FORMAT, `Ability onNewWant`);
        this.appContinuity(want, launchParam);
      }
    
      appContinuity(want: Want, launchParam: AbilityConstant.LaunchParam) {
        if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
          // ...
          let mailInfo: ContinuationData = new ContinuationData(undefined, undefined, undefined, undefined, undefined,
            undefined, undefined, undefined, undefined, undefined);
          this.distributedObject = distributedDataObject.create(this.context, mailInfo);
          // Add a data restored listener.
          try {
            this.distributedObject.on('status',
              (_sessionId: string, _networkId: string, status: 'online' | 'offline' | 'restored') => {
                if (status === 'restored') {
                  if (!this.distributedObject || !this.distributedFileUtil) {
                    return;
                  }
                  // Use the distributed object migration to transfer the basic page data
                  AppStorage.setOrCreate('basicDataStr', this.distributedObject['basicDataStr'] ?? '');
                  AppStorage.setOrCreate('basicDataNum', this.distributedObject['basicDataNum'] ?? undefined);
                  AppStorage.setOrCreate('distributedData', this.distributedObject['distributedData'] ?? undefined);
                  // ...
                  AppStorage.setOrCreate('curPageInfos', this.distributedObject['curPageInfos'] ?? undefined);
                }
              });
          } catch (err) {
            hilog.error(DOMAIN, TAG, FORMAT, `On status failed. Cause code: ${err.code}`);
          }
          let sessionId: string = want.parameters?.distributedSessionId as string;
          this.distributedObject.setSessionId(sessionId).catch((err: BusinessError) => {
            hilog.info(DOMAIN, TAG, FORMAT, `SetSessionId failed. Cause code: ${err.code}`);
          });
          try {
            // Restore window stage with new LocalStorage instance
            this.context.restoreWindowStage(this.storage);
          } catch (err) {
            hilog.error(DOMAIN, TAG, FORMAT, `RestoreWindowStage failed. Cause : ${err}`);
          }
        }
      }
    
      // ...
    }

[h2]Migrating File Assets

Sample Code