目录

Redirection for Social Sharing

Introduction

With the development of social networking and mobile apps, users are increasingly accustomed to quickly sharing articles, products, or activities through social platforms, and expect invited friends to be able to access the target content with just one click. To meet this requirement, the system provides the App Linking technology to implement efficient, secure, and excellent social sharing redirection.

Use cases:

Typical Scenarios

App Linking supports three typical redirection scenarios and intelligently routes users based on their device status.

[h2]Scenario 1: Target App Installed

When a user taps the shared link, the system directly opens the target app and displays the content details page, without the need to go through the browser. This one-tap access greatly improves the convenience and conversion rate.

[h2]Scenario 2: Target App Not Installed, with Direct Access to AppGallery Configured

If the user has not installed the target app and you have configured the function of direct access to AppGallery, the user will be redirected to the app details page on AppGallery after clicking the link.

After the installation is complete, the first time the user opens the app, the deferred link function automatically navigates the user to the original shared content, eliminating the need for the user to search or perform any additional operations.

[h2]Scenario 3: Target App Not Installed and Direct Access to AppGallery Not Configured (Web Page Available)

After a user taps the link, the system opens the web page through the browser, and the user can directly view the content.

A download button can be provided on the web page to guide users to install the app for a better experience. After the app is installed, users can still access the original content through the deferred link.

For apps that do not provide web pages, it is recommended that the function of direct access to AppGallery be enabled to avoid experience disruption caused by content access failures.

How to Implement

Based on HTTPS domain name verification and cloud configuration, App Linking automatically determines whether the target app is installed and whether a web page is provided, and then performs the optimal redirection.

The following figure shows the process of redirection from a social app.

The preceding figure shows the complete process from sharing content to a friend to the friend receiving and redirecting to the content. The system automatically selects the optimal path based on the recipient's device status, ensuring a seamless and smooth experience for the user in any situation.

  1. User A generates a link of App Linking in a social app.
  2. User B receives and taps the link. The system performs the corresponding operation (redirecting to the target app, AppGallery, or web page) based on the device environment.
  3. If user B has not installed the social app and has configured the redirection to the app market, the app market details page is displayed to guide the user to install the app. After the app is installed, the content page is displayed when the user opens the app for the first time, achieving a closed-loop experience.

This section describes how to use App Linking to implement redirection in a social sharing app. You can determine whether to configure the redirection path to the app market based on service requirements. The main development steps for social apps are as follows:

Development Procedure

[h2]Configuring App Linking

  1. Enable App Linking.

  2. Associate a domain name with your app.

  3. Create an associated website domain name for your app in AppGallery Connect.

  4. Configure the associated website domain name in the module.json5 file.

    // entry/src/main/module.json5
    {
      "module": {
        // ...
        "abilities": [
          {
            "name": "EntryAbility",
            // ...
            "exported": true,
            "skills": [
              {
                "entities": [
                  "entity.system.home",
                  // entities must contain "entity.system.browsable"
                  "entity.system.browsable"
                ],
                "actions": [
                  "ohos.want.action.home",
                  // Actions must contain "ohos.want.action.viewData"
                  "ohos.want.action.viewData"
                ],
                "uris": [
                  {
                    // The scheme must be configured as https
                    "scheme": "https",
                    // The host must be configured as the associated domain name
                    "host": "******",
                    "path": ""
                  }
                ],
                // domainVerify must be set to true
                "domainVerify": true
              }
            ]
          }
        ],
        // ...
      }
    }
  5. Verify the app launch effect.

    1. Manually sign your app.

    2. Compile and package the app, and install it on the debugging device.

    3. Run the following command to query the app domain name verification result:

      hdc shell hidumper -s AppDomainVerifyManager

      After running the hidumper command, you can view the success message on the console.

      BundleName:
        appIdentifier: 123456789
          domain verify status:
            https://www.example.com: success

      Save the generated link of App Linking to the memo app. You can tap the link in the memo app to launch the corresponding social app in one-click mode to test whether the social app can be successfully launched through the link of App Linking. This method can be used to verify the App Linking configuration and the app response.

[h2]Integrating the Sharing Panel

Social apps can integrate Share Kit to display the sharing panel for sharing App Linking links of article details. After the recipient taps the link, they will be directly redirected to the target app. For details, please refer to Sharing a Link of App Linking to Go to a Specified In-app Page.

Set the shared content type to utd.UniformDataType.HYPERLINK, and pass the generated App Linking URL (with the unique content ID) in the content field.

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor } from '@kit.ArkData';
import { Logger } from '../common/Logger';
// ...
// entry/src/main/ets/pages/Detail.ets
@Entry
@Component
struct Detail {
  // ...
  private async share() {
    try {
      let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
      // ...
      // To construct ShareData, you need to configure a valid data message
      let shareData: systemShare.SharedData = new systemShare.SharedData({
        // The type of data shared is a link
        utd: uniformTypeDescriptor.UniformDataType.HYPERLINK,
        // The shared App Linking link is replaced with the real address here
        content: `https://hello.dra.agchosting.link?aid=${this.article?.aId}`,
        // ...
      });
      // The sharing panel is displayed
      let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
      controller.show(context, {
        previewMode: systemShare.SharePreviewMode.DEFAULT,
        selectionMode: systemShare.SelectionMode.SINGLE
      })
        .then(() => {
          Logger.info(TAG, 'ShareController show success.');
        })
        .catch((error: BusinessError) => {
          Logger.error(TAG, `ShareController show error. code: ${error.code}, message: ${error.message}`);
        });
    } catch (err) {
      let error = err as BusinessError;
      Logger.error(TAG, `share err, code: ${error.code}, mesage: ${error.message}`);
    }
  }

  // ...
}

[h2]Processing in the App and Redirecting to a Specified Page

When a user taps the shared link to launch the app, the article details page is displayed in either of the following scenarios:

  1. The app is not running in the background: If the app is cold started (that is, it is not running in the background), you need to obtain the unique article ID (aid) from the link in the onCreate() method.

    // entry/src/main/ets/entryability/EntryAbility.ets
    import { BusinessError } from '@kit.BasicServicesKit';
    import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { window } from '@kit.ArkUI';
    import { url } from '@kit.ArkTS';
    import { Logger } from '../common/Logger';
    
    const DOMAIN = 0x0000;
    const TAG = 'EntryAbilityLogTag';
    
    export default class EntryAbility extends UIAbility {
      private mAid: string = '';
    
      private getAid(want: Want): string {
        let uri = want?.uri;
        let aid: string = '';
        // Parse the parameters to obtain the app linking
        if (uri) {
          try {
            let urlObject = url.URL.parseURL(want?.uri);
            aid = urlObject.params.get('aid') as string;
            hilog.info(DOMAIN, 'testTag', '%{public}s', `getAid aid:${aid}`);
          } catch (err) {
            let error = err as BusinessError;
            Logger.error(TAG, `onAddForm err, code: ${error.code}, mesage: ${error.message}`);
          }
        }
        return aid;
      }
    
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
        try {
          this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
        } catch (err) {
          let error = err as BusinessError;
          Logger.error(TAG, `setColorMode err, code: ${error.code}, mesage: ${error.message}`);
        }
        this.mAid = this.getAid(want);
      }
    
      // ...
    }

    In the onWindowStageCreate() callback, use the windowStage.loadContent() method to load the URL of the details page, which is pages/Detail.

    // entry/src/main/ets/entryability/EntryAbility.ets
    onWindowStageCreate(windowStage: window.WindowStage): void {
    
      let pageUrl: string = 'pages/Index';
      if (this.mAid && this.mAid !== '') {
        pageUrl = 'pages/Detail';
        AppStorage.setOrCreate('aid', this.mAid);
      }
    
      windowStage.loadContent(pageUrl, (err) => {
        if (err.code) {
          hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
          return;
        }
        try {
          // ...
          hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
        } catch (err) {
          let error = err as BusinessError;
          Logger.error(TAG, `loadContent err, code: ${error.code}, mesage: ${error.message}`);
        }
      });
    }
  2. If the app is running in the background, it will switch from the background to the foreground. In this case, you need to obtain the unique article ID (aid) from the link in the onNewWant() method and save it to AppStorage.

    export default class EntryAbility extends UIAbility {
      private mAid: string = '';
    
      private getAid(want: Want): string {
        // ...
      }
    
      // ...
      onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        let aid: string = this.getAid(want);
        if(aid){
          AppStorage.setOrCreate('aid',aid);
          AppStorage.setOrCreate('newWantFlag',true);
        }
      }
    
      // ...
    }

    On the home page, obtain aid through StorageLink and use the UIContext.getRouter().pushUrl() method to redirect to the page.

    @StorageLink('newWantFlag') @Watch('newWantFlagChange') isNewWant: boolean = false;
    
    newWantFlagChange() {
      if (this.isNewWant && AppStorage.has('aid')) {
        let aid: string = AppStorage.get('aid') as string;
        if (aid) {
          this.isNewWant = false;
          this.getUIContext().getRouter().pushUrl({
            url: 'pages/Detail',
            params: {
              aid: aid
            }
          }).catch((error: BusinessError) => {
            Logger.error(TAG, `pushUrl err, code: ${error.code}, mesage: ${error.message}`);
          });
        }
      }
    }
  3. After obtaining the unique article ID (aid), load the article details on the details page.

    // entry/src/main/ets/pages/Detail.ets
    @Entry
    @Component
    struct Detail {
      // ...
      private article: Article | undefined;
    
      aboutToAppear(): void {
        if (this.aid && this.aid !== '') {
          this.article = getArticleById(this.aid);
        } else {
          let params = this.getUIContext().getRouter().getParams() as Record<string, string>;
          this.article = getArticleById(params.aid);
        }
      }
    
      // ...
    }

[h2](Optional) Web Page Development and Deployment

If the app is not installed and direct access to AppGallery is not configured, the system will open the web page in the browser. Proper web page development is crucial to enhancing user experience, especially when used in conjunction with the deferred link function.

Web Page UA Adaptation

First, accurately identify HarmonyOS devices to implement proper redirection and content adaptation. The User-Agent (UA) string of a HarmonyOS device usually contains specific identification information. You need to parse the UA string and determine the system type (such as the OS name) and version number.

If UA adaptation is not correctly performed, the following problems may occur:

Identify the HarmonyOS system through the {OSName} field in the User-Agent, and identify the HarmonyOS system and its version through the {OSName} and {OSVersion} fields in the User-Agent.

function matchHarmonyOS() {
  // Determine whether the recognition system is HarmonyOS.
  const isHarmonyOS = /HarmonyOS/i.test(navigator.userAgent);
  // Get system version number
  const matches = navigator.userAgent.match(/OpenHarmony (\d+\.?\d*)/);
  return isHarmonyOS && matches?.length && Number(matches[1]) >= 5;
}

function openLink() {
  if (matchHarmonyOS()) {
    // Launch the application through app linking.
    // ...
  } else {
    // Redirect logic for other platforms
  }
}

For details, please refer to Developing User-Agent.

Implementing the intelligent redirection logic

The web page must provide the following two key functions:

  1. Open button: attempts to start the installed app.
  2. Download button: directs users who have not installed the app to the AppGallery.

If the app has been installed, the user can click the Open button to directly open the social app and go to the article details page. The redirection link is the one configured in Configuring App Linking, for example, https://www.example.com/. You can set the window.location.href attribute to implement page redirection.

function openLink() {
  if (matchHarmonyOS()) {
    // Launch the application through app linking.
    // Replace with a real usable app linking link.
    window.location.href = 'https://www.example.com?aid=' + aid;
  } else {
    // Redirect logic for other platforms
  }
}

If a user has not installed the social app, the user can tap the download button to go to the AppGallery details page to download and install the app. You can use the App Linking link of AppGallery and set the window.location.href attribute to implement page redirection.

function toAppgallery() {
  // Replace with a real usable application market app linking link.
  window.location.href = 'https://appgallery.huawei.com/app/detail?id=com.huawei.hmsapp.books';
}

Combination of deferred links and web page

The combination of web pages and deferred links is key to creating a complete user experience. After a user installs an app through a web page, a deferred link can be used to automatically redirect the user to the original content when the user opens the app for the first time.

To ensure that App Linking works properly, pay attention to the following:

  • The domain name of the web page must be different from that configured for App Linking. Otherwise, the system will preferentially use the browser to open the link.
  • Recommended deployment architecture:

FAQs

[h2]How can I check whether App Linking has been successfully configured in AppGallery Connect?

  1. Sign in to AppGallery Connect and click Development and services.
  2. Find and click the project to which your HarmonyOS app belongs in the project list.
  3. In the navigation pane on the left, choose Grow > App Linking to view the configuration status of the App Linking URL. If the configuration is successful, App Linking has been successfully configured in AppGallery Connect.

[h2]What can I do if App Linking fails to be configured in AppGallery Connect?

Symptom

The following figure shows the configuration status of the App Linking URL on the App Linking menu bar. A red dot is displayed, and a message is displayed indicating that the configuration fails.

Solution

If the preceding check results are normal, contact the website O&M personnel for assistance.

[h2]What should I do if the configuration is successful in AppGallery Connect but the app cannot be launched after the configuration is completed for the target app?

Symptom

The link address is successfully configured in AppGallery Connect, but after the link is configured for the target app, the app fails to be launched by calling openLink() or through other methods.

Possible causes

  1. The App Linking URL configured in AppGallery Connect ends with a slash (/).
  2. The link configured in the module.json5 file of the target app is inconsistent with that configured in AppGallery Connect. As a result, the app cannot be started.
  3. The app is not manually signed using a certificate obtained from AppGallery Connect.
  4. The network where the developer is located has access restrictions.
  5. The module.json5 file is incorrectly configured.

Solution

  1. Check the App Linking URL configured in AppGallery Connect. Currently, the URL cannot end with a slash (/). Check whether the URL configured in AppGallery Connect ends with a slash (/).
  2. Check whether the link configured in the module.json5 file is the same as that configured in AppGallery Connect. For example, if https://www.huawei.com is configured in AppGallery Connect, but https://developer.huawei.com is used in the code, the link is incorrect.
  3. Manually apply for a certificate and profile in AppGallery Connect and sign the app. For details, please refer to Verifying the App Launch Effect.
  4. Switch to another network.
  5. Check whether the module.json5 configuration meets the requirements based on the following code:
    // entry/src/main/module.json5
    {
      "module": {
        // ...
        "abilities": [
          {
            "name": "EntryAbility",
            // ...
            "exported": true,
            "skills": [
              {
                "entities": [
                  "entity.system.home",
                  // entities must contain "entity.system.browsable"
                  "entity.system.browsable"
                ],
                "actions": [
                  "ohos.want.action.home",
                  // Actions must contain "ohos.want.action.viewData"
                  "ohos.want.action.viewData"
                ],
                "uris": [
                  {
                    // The scheme must be configured as https
                    "scheme": "https",
                    // The host must be configured as the associated domain name
                    "host": "******",
                    "path": ""
                  }
                ],
                // domainVerify must be set to true
                "domainVerify": true
              }
            ]
          }
        ],
        // ...
      }
    }

[h2]How can I handle exceptions of cross-app page redirection from a web page?

Symptom

After a user taps a link on the chat screen of a social app to access a web page, an exception occurs when the user attempts to switch from web page A of the app to web page B of another app. For example, the user switches from the broadband recharge page of app A to the payment page of app B, but an exception occurs on the payment page of app B.

Possible causes

  1. The UA identifier of the target web page B is not adapted to HarmonyOS devices or browser environments, causing compatibility issues.
  2. Resources on the target web page B fail to be loaded.

Solution

  1. Adapt the UA identifier. Ensure that the web page B adapts to the UA identifier of the HarmonyOS device and the matching browser so that the device can be correctly identified and the corresponding page or platform can be redirected to. For details, please refer to Developing User-Agent.
  2. Check the resource loading of web page B.

[h2]How can I handle app redirection exceptions on a web page?

Symptom

After a user taps a link on the chat screen of a social app to go to a web page, an exception occurs when the user attempts to redirect to an app through operations on the web page. For example:

  1. No response after tapping Open.
  2. After the user taps the download button, the user is redirected to an incorrect platform, or a message is displayed, prompting the user to download the APK directly.

Possible causes

  1. If the target app does not respond when a user taps the Open button, the redirection logic (for example, App Linking) may not be correctly configured for the target app, or an error may have occurred during the configuration.
  2. The web page does not respond when the Open button is tapped because the link used by the web page is incorrect.
  3. If the target app is not installed and the user taps the download button, the app download logic is triggered and the user is redirected to the app download web page. However, if the web page does not correctly adapt to the UA identifier of the HarmonyOS device, the user is redirected to an incorrect platform or a message is displayed, prompting the user to download the APK package directly.

Solution

Sample Code