目录

Common Continuation

Overview

Continuation is a user experience optimization technology. This feature enables users to seamlessly switch from the app on one device to the same app on a new device if there is a suitable device nearby. This topic describes how to implement efficient continuation of browsing progress in three scenarios: long list, media playback, and web browsing. With the continuation feature, users can easily resume their previous browsing progress when switching devices, greatly enhancing convenience and continuity, and providing a seamless, smooth experience.

How to Implement

The continuation relies on the underlying distributed framework and DSoftBus. You only need to enable continuation, save data on the source device, and restore data on the target device. For details about the operation mechanism, see Working Principles.

How to Develop

To achieve progress continuation, it is essential to ensure that progress data can be accurately transmitted between devices and kept in sync. During actual development, you may encounter various complex continuation requirements. The first task is to deeply analyze the data that is critical to continuation control. When continuation is initiated on the source device, data needs to be saved. When the progress is resumed on the target side, the data must be accurately restored to ensure the progress continuity and data consistency across devices. This section describes how to configure an app to use the continuation capability, and how to save and restore data to implement seamless continuation of the app. The development process is as follows:

  1. Enable app continuation.

    In the abilities field of the module.json5 file, set continuable to true, which indicates that the UIAbility can be migrated. The default value is false. If this parameter is not set or explicitly set to false, the UIAbility will be identified by the system as non-migratable.

    {
      "module": {
        // ...
        "abilities": [
          {
            // ...
            "continuable": true
          }
        ],
        // ...
      }
    }
  2. Save data on the source device.

    When the target device taps the continuation icon, the source device triggers the onContinue() API in UIAbility. In this API, you can save the data to be migrated in wantParam in the form of key-value pairs and return AbilityConstant.OnContinueResult.AGREE to indicate that the app agrees to the migration.

    async onContinue(wantParam: Record<string, Object>): Promise<AbilityConstant.OnContinueResult> {
      // 1.1 Retrieve the data to be connected and transmit it via wantParam.
      let continueIndex = AppStorage.get('continueIndex') as number;
      wantParam.continueIndex = continueIndex;
      let currentOffset = AppStorage.get('currentOffset') as number;
      wantParam.currentOffset = currentOffset;
      let continueHeight = AppStorage.get('listItemHeight') as number;
      wantParam.continueHeight = continueHeight;
      let currentTime = AppStorage.get('currentTime') as number;
      wantParam.continueTime = currentTime;
      let videoIndex = AppStorage.get('videoIndex') as number;
      wantParam.continueItem = videoIndex;
      let flag = AppStorage.get('flag') as boolean;
      wantParam.flag = flag;
      let url = AppStorage.get('pageUrl') as string;
      wantParam.pageUrl = url;
      let distance = AppStorage.get('scrollDistance') as number;
      wantParam.scrollDistance = distance;
      let breakpoint = AppStorage.get(BreakpointConstants.BREAKPOINT_NAME) as string;
      wantParam.breakpoint = breakpoint;
      let pageInfos = AppStorage.get('pageInfos') as NavPathStack;
      let pageArr = pageInfos.getAllPathName();
      let currentPage = '';
      if (pageArr.length > 0) {
        currentPage = pageArr[pageArr.length - 1];
      }
      AppStorage.setOrCreate('continue', false);
      wantParam.currentPage = currentPage;
    
      return AbilityConstant.OnContinueResult.AGREE;
    }
  3. Restore data on the target device.

    After the source saves data and agrees to the migration, the target device can start the app. You can restore data in the onCreate() or onNewWant() lifecycle callback of UIAbility. If Ability is started based on LaunchReason.CONTINUATION, you can obtain the saved key-value pair data from want.parameters.

    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
      GlobalContext.getContext().setObject('abilityWant', want);
      GlobalContext.getContext().setObject('context', this.context);
      if (want.parameters) {
        if (want.parameters.currentTime) {
          GlobalContext.getContext().setObject('currentTime', want.parameters.currentTime);
        }
      }
      try {
        this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
      } catch (e) {
        hilog.error(0x000, 'progress', `setColorMode error ${JSON.stringify(e)}`);
      }
      if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
        if (want.parameters) {
          this.continueRestore(want);
        }
      }
      hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
    }

    You can extract the data restoration method as a public method, which can be called in onCreate() or onNewWant() of UIAbility.

    continueRestore(want: Want) {
      if (!want.parameters) {
        hilog.error(0x0000, 'EntryAbility', 'missing sessionId');
        return;
      }
      let currentPage = want.parameters.currentPage as string;
      AppStorage.setOrCreate('currentPage', currentPage);
      want.parameters.continueIndex && AppStorage.setOrCreate('continueWaterOffset', want.parameters.continueIndex);
      want.parameters.currentOffset && AppStorage.setOrCreate('continueOffset', want.parameters.currentOffset);
      want.parameters.continueHeight && AppStorage.setOrCreate('continueHeight', want.parameters.continueHeight);
      AppStorage.setOrCreate('continueEntry', true);
      AppStorage.setOrCreate('setCurrentOffset', true);
      want.parameters.continueTime && AppStorage.setOrCreate('currentTime', want.parameters.continueTime);
      want.parameters.continueItem && AppStorage.setOrCreate('videoIndex', want.parameters.continueItem);
      want.parameters.continueItem && AppStorage.setOrCreate('videoSelect', want.parameters.continueItem);
      want.parameters.flag && AppStorage.setOrCreate('flag', want.parameters.flag);
      AppStorage.setOrCreate('continue', true);
      AppStorage.setOrCreate('continueRestore', true);
      want.parameters.pageUrl && AppStorage.setOrCreate('pageUrl', want.parameters.pageUrl);
      want.parameters.scrollDistance && AppStorage.setOrCreate('scrollDistance', want.parameters.scrollDistance);
      want.parameters.breakpoint && AppStorage.setOrCreate('continueBreakpoint', want.parameters.breakpoint);
    
      try {
        this.context.restoreWindowStage(new LocalStorage());
      } catch (e) {
        hilog.error(0x000, 'progress', `restoreWindowStage error ${JSON.stringify(e)}`);
      }
    }

Long List Continuation

[h2]When to Use

In social media and news apps, users often need to browse long lists of content. When a user scrolls to a certain position in the list, they may switch to another device and expect the scroll position to be automatically restored after the switch, avoiding repeated operations. You can use the continuation capability to improve user experience in such scenarios.

[h2]How to Implement

Long lists are typically used to store a large amount of information and can be encapsulated using List, Grid, Scroll, and WaterFlow. The system provides the distributed migration identifier to restore the progress status when these components are used. This method is easy to call. The following is an example:

WaterFlow({ footer: this.footStyle, scroller: this.waterFlowScroller }) {
  // ...
}
.restoreId(1)

However, it can be used in limited scenarios and versions. For details, see restoreId. If you need to perform more custom settings during development to improve user experience, perform the following steps:

[h2]How to Develop

  1. Enable app continuation.
  2. Listen for the change in the long list progress in the onDidScroll() API of the Scroll component.
    Scroll(this.scroller) {
      // ...
    .onDidScroll((xOffset: number, yOffset: number, scrollState: ScrollState) => {
      if (!this.setCurrentOffset) {
        this.currentOffset = this.scroller.currentOffset().yOffset;
      }
    })
  3. In the onContinue() callback of UIAbility, save the progress data to wantParam. For details, see Save data on the source device.
  4. In the onNewWant() and onCreate() callbacks of UIAbility, restore data from want.parameters. For details, see Restore data on the target device.
  5. Restore the browsing status in the onDidBuild() event.
    onDidBuild(): void {
      hilog.info(0x000, 'progress', `onDidBuild ${this.setCurrentOffset} ${this.continueOffset}`);
      if (this.setCurrentOffset) {
        this.scroller.scrollTo({ xOffset: 0, yOffset: this.continueOffset });
        this.setCurrentOffset = false;
      }
    }

Media Playback Continuation

[h2]When to Use

In video playback scenarios, a user may switch to another device while watching a video, for example, from a mobile phone to a tablet or PC. After switching devices, the user expects to continue watching the video from the previous playback position instead of starting over. In such scenarios, you can use the continuation function to improve user experience.

[h2]How to Implement

The content to be continued in media playback continuation mainly includes the series count in the playlist, playback status, and progress. You can also customize other playback settings to be continued to enhance user experience.

[h2]How to Develop

  1. Enable app continuation.
  2. Call avPlayer.on('timeUpdate') to listen for the change in the media playback progress.
    this.avPlayer.on('timeUpdate', (time: number) => {
      if (this.isSliderAction) {
        return;
      }
      this.currentTime = time;
      AppStorage.set('currentTime', this.currentTime)
    });
  3. In the onContinue() callback of UIAbility, save the current playback time this.time to wantParam. For details, see Save data on the source device.
  4. In the onNewWant() and onCreate() callbacks of UIAbility, restore data from want.parameters. For details, see Restore data on the target device.
  5. After avPlayer is initialized, check whether the current state is the continuation state. If yes, call the encapsulated videoSeek() method for adjusting the video progress to restore the playback status before the continuation.
    if (this.continue) {
      this.videoSeek(continueTime);
      this.continue = false;
      AppStorage.set('continue', false);
    }

Web Browsing Continuation

[h2]When to Use

In web browsing scenarios, a user may switch to another device while browsing a web page. After the user switches to another device, the previous web page URL and scroll position are expected to be restored to maintain the continuity of the browsing context. In such scenarios, you can use the continuation function to further improve user browsing experience.

[h2]How to Implement

The system provides the Web components to display web page content in apps. When the Web component carries a large amount of information, it is crucial to maintain the continuation of browsing progress. To implement continuous display of content, the current scrolling position needs to be passed to maintain the continuation, which is similar to the long list continuation. This can be achieved by using the runJavaScript() API to obtain and restore the scrolling position. The procedure is as follows:

[h2]How to Develop

  1. Enable app continuation.
  2. Use the onTouch() event to listen for the sliding page and use runJavaScript() to obtain the distance between the scroll bar and the top of the page.
  3. In the onContinue() callback, save this.scrollDistance to wantParam. For details, see Save data on the source device.
  4. In the onNewWant() and onCreate() callbacks, restore data from want.parameters. For details, see Restore data on the target device.
  5. Call runJavaScript() in the onPageEnd() callback to restore the progress.
    Web({ src: this.pageUrl, controller: this.controller })
    // ...
      .onPageEnd(async () => {
        // ...
        if (this.pageUrl.includes('product_list') && this.continueRestore) {
          this.controller.runJavaScript('javascript:document.getElementById("productList").scrollTop = ' +
          this.scrollDistance);
        }
        this.pageUrl = this.controller.getUrl();
        let result =
          await this.controller.runJavaScript('javascript:document.getElementById("productList").scrollTop');
        this.scrollDistance = Number(result);
      })
      // ...
      .onTouch(async (event: TouchEvent) => {
        if (event.type === TouchType.Up) {
          if (this.pageUrl.includes('product_list')) {
            let result =
              await this.controller.runJavaScript('javascript:document.getElementById("productList").scrollTop');
            this.scrollDistance = Number(result);
          }
        }
      })

Sample Code