目录

Social Sharing Redirection

Overview

As content socialization and mobile apps continue to evolve, users have become accustomed to quickly sharing articles, products, or events through social platforms. They expect their friends to be able to directly access the target content with just one tap. To meet this requirement, the system provides App Linking, which delivers an efficient, secure, and seamless user experience for social sharing redirection.

An example use scenario is as follows:

Typical Scenarios

App Linking supports three typical redirection scenarios, with intelligent routing based on the target device status.

[h2]Scenario 1: Target Application Installed

When users tap the shared link, the system directly launches the target app and navigates to the content details page without going through the browser. This one-tap access significantly enhances convenience and conversion rates.

[h2]Scenario 2: Target Application Not Installed, but Direct Access to AppGallery Configured

If the target app is not installed and the direct access to AppGallery feature is configured, tapping the link will take users directly to the app details page on AppGallery.

After installation, the first launch of the app will automatically navigate to the originally shared content through the deferred link, eliminating the need for users to search or perform additional operations.

[h2]Scenario 3: Target Application Not Installed, Direct Access to AppGallery Not Configured, but a Web Page Available

When users tap the link, the system opens the web page in the browser, allowing them to directly view the content.

The web page can provide a Download button to guide users to install the app for a better experience. After installation, they can still access the original content through the deferred link.

For apps that do not provide a web page, you are advised to configure direct access to AppGallery to avoid a fragmented user experience caused by content access failure.

How to Implement

App Linking is based on HTTPS domain name verification and cloud configuration. It automatically determines whether the target app is installed and whether a web page is provided, and makes the optimal redirection. App Linking offers the following advantages:

The flowchart for social sharing app redirection is shown below.

The above figure illustrates the complete process from sharing content to receiving and redirection. The system automatically selects the best path based on the target device status, ensuring a coherent and smooth experience in all scenarios.

  1. User A generates an App Linking shared link in a social app.
  2. User B receives and taps the link. The system takes corresponding actions (redirecting to the target app, AppGallery, or web page) based on the device environment.
  3. If redirection to AppGallery and app installation are carried out in between, the first launch of the target app can automatically navigate to the content page, ensuring a closed-loop experience.

This topic will detail the development steps for using App Linking to achieve redirection in social sharing apps. You can decide whether to configure direct access to AppGallery based on service requirements. The main development steps for social apps are as follows:

How to Develop

[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": [
                  {
                    // scheme must be configured as https.
                    "scheme": "https",
                    // host must be configured as the associated domain name.
                    "host": "******",
                    "path": ""
                  }
                ],
                // domainVerify must be set to true.
                "domainVerify": true
              }
            ]
          }
        ],
        // ...
      }
    }
  5. Verify the effect of app launch.
    1. Manually sign the app.
    2. Compile, package, and install the app to 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 will see a success message on the console.

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

      Save the generated App Linking link to the Notepad app. By tapping the link in the Notepad app, you can directly launch the corresponding social app to check whether the social app can be successfully started through the App Linking link. This method can be used to verify the correctness of the App Linking configuration and the response of the app.

[h2]Integrating the Sharing Panel

You can integrate Share Kit into your app to open the sharing panel, which is used to share the App Linking link of the article details. When the recipient taps the link, they can be directly redirected to the target app. For details, see 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 link (with a 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
      })
      // ...
    } catch (err) {
      let error = err as BusinessError;
      Logger.error(TAG, `share err, code: ${error.code}, mesage: ${error.message}`);
    }
  }

  // ...
}

[h2]Processing and Redirecting to a Specified Page Within the Application

When users tap the shared link and launch the app, there are two scenarios for redirecting to the article details page:

  1. App not running in the background: If the app starts from a cold boot, obtain the unique article ID (aid) from the link in the onCreate() API.
    // 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() API to load the URL of the details page as 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. App already running in the background: If the app is already in the background, it will switch from the background to the foreground. In this case, obtain the unique article ID (aid) from the link in the onNewWant() API 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);
        }
      }
    
      // ...
    }

    Obtain the aid on the home page through StorageLink and perform page redirection using the UIContext.getRouter().pushUrl() API.

    @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 data 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) Configuring Direct Access to AppGallery and Deferred Linking

To improve user experience for users who do not have the app installed, you can configure the direct access to AppGallery feature to guide users to download and install the app.

In the App Linking service in AppGallery Connect (AGC), enable direction access to AppGallery.

After the configuration, when users tap the shared App Linking link in MeeTime, if the target app is not installed on the device, the system redirects users to the app details page on AppGallery, where they can download and install the app in one tap.

You also need to implement the deferred link feature to ensure that the content can be directly accessed upon the first launch after the app is installed.

After the app is installed, you can use the deferred link to redirect users to the article details page when they open the app for the first time. This process not only optimizes user experience but also helps improve the conversion rate of links.

Use deferredLink.popDeferredLink() to obtain the original App Linking link and redirect to the corresponding content details page based on the link.

// entry/src/main/ets/pages/Index.ets
import { BusinessError } from '@kit.BasicServicesKit';
import { deferredLink } from '@kit.AppLinkingKit';
import { url } from '@kit.ArkTS';
import { Logger } from '../common/Logger';
// ...
@Entry
@Component
struct Index {
  // ...
  aboutToAppear(): void {
    // Get the deferred link parameter and go to the details page
    deferredLink.popDeferredLink().then((link: string) => {
      Logger.info(TAG, `Succeeded in getting deferred link, result: ${link}`);
      if (link) {
        // Get the link parameters
        let urlObject = url.URL.parseURL(link);
        let aid = urlObject.params.get('aid') as string;
        // Go to the details component
        this.getUIContext().getRouter().pushUrl({
          url: 'pages/Detail',
          params: {
            aid: aid
          }
        });
      }
    }).catch((error: BusinessError) => {
      Logger.error(TAG, `Failed to get deferred link. code: ${error.code}, message: ${error.message}`);
    });
  }
  // ...
}

[h2](Optional) Developing and Deploying a Web Page

If the app is not installed and direct access to AppGallery is not configured, the system opens the web page. Proper web page development is a key to improving user experience, especially when combined with deferred links.

Web Page UA Adaptation

It is necessary to accurately identify HarmonyOS devices to achieve appropriate redirection and content adaptation. The User-Agent (UA) string of HarmonyOS devices usually contains specific identification information. You should parse the UA string and determine the system type (for example, OS name) and version number.

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

Identify the HarmonyOS system based on the {OSName} field in UserAgent, and identify the HarmonyOS system and version based on the {OSName} and {OSVersion} fields in UserAgent.

function matchHarmonyOS() {
  // Determine whether the recognition system is HarmonyOS.
  const isHarmonyOS = /OpenHarmony/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, see Developing User-Agent.

Intelligent Redirection Logic Implementation

The web page needs to provide two key features through the following buttons:

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

When the app is installed, users can tap the Open button to jump to the article details page within the social app. The redirection link is the link configured in Configuring App Linking, for example, https://www.example.com/. Page redirection is performed by setting the window.location.href property.

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
  }
}

When the app is not installed, users can tap the Download button to jump to the app details page on AppGallery, where they can download and install the app. You can use the App Linking link and perform page redirection by setting the window.location.href property.

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 Pages

The combination of web pages and deferred links is a key to creating a complete user experience. After users install the app through the web page, they can automatically jump to the original content when they first open the app through the deferred link.

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

  • The web page domain name should be different from the domain name configured for App Linking. Otherwise, the system will preferentially use the browser to open the link.
  • Recommended deployment architecture:
    • A primary domain name (https://www.example.com) is configured as the App Linking domain name and used to deploy the landing page.
    • A subdomain name (https://m.example.com/detail) is used to deploy the actual content page.
    • The landing page redirects users to the content page.

FAQs

[h2]How do I check whether App Linking is successfully configured in AGC?

  1. Sign in to AppGallery Connect and click Development and services.
  2. Click the project to which your HarmonyOS app belongs.
  3. In the navigation tree on the left, choose Grow > App Linking to view the link configuration status. If Successful is displayed in Status, App Linking is successfully configured in AGC.

[h2]What should I do if App Linking configuration fails in AGC?

Symptom

On the App Linking page, Failed is displayed in Status, and related error information is displayed.

Solution

If the problem still persists, contact the technical support personnel to solve the problem.

[h2]What should I do if the target app fails to start when the link configuration is successful in AGC?

Symptom

The link is successfully configured in AGC, however, the target app cannot be started by openLink() or other means.

Possible Causes

  1. The link configured in AGC ends with a slash (/).
  2. The link configured in the module.json5 file of the target app is different from that configured in AGC.
  3. The app does not request a certificate to sign the app in AGC.
  4. The network access is restricted.
  5. The module.json5 file is incorrectly configured.

Solution

  1. Check whether the link configured in AGC ends with a slash (/). Currently, the URL cannot end with a slash (/).
  2. Check whether the link configured in module.json5 is the same as that configured in AGC. For example, https://www.huawei.com is configured in AGC, while https://developer.huawei.com is used in the code.
  3. Check whether the app is signed. If not, request a certificate and profile in AppGallery Connect and sign the app. For details, see Verifying the App Launch Effect.
  4. Check whether network access is restricted. If yes, use a network available.
  5. Check whether the module.json5 file is correctly configured. The following is an example of correct configuration.
    // 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": [
                  {
                    // scheme must be configured as https.
                    "scheme": "https",
                    // host must be configured as the associated domain name.
                    "host": "******",
                    "path": ""
                  }
                ],
                // domainVerify must be set to true.
                "domainVerify": true
              }
            ]
          }
        ],
        // ...
      }
    }

[h2]What should I do if the web page is displayed abnormally after a link in the social app is tapped?

Symptom

After a link in the social app is tapped, the web page appears blank, cannot interact normally, or is loaded abnormally.

Possible Causes

  1. The UA of the web page does not adapt to HarmonyOS devices or browser environments, resulting in compatibility issues.
  2. The web page may not be fully developed or contains errors (for example, resource loading failure or backend service exception).
  3. The link address is incorrect. As a result, the target page cannot be loaded.

Solution

  1. Adapt the UA. Ensure that the web page adapts to the UA of HarmonyOS devices and the accompanying browser to correctly identify the device and redirect to the corresponding page or platform. For details, see Developing User-Agent.
  2. Check the completeness of page development. Check whether page resources are properly loaded and whether the backend API returns correct data.
  3. Verify the link address. Ensure that the link address sent in the chat screen of the social app is correct.

[h2]What should I do if cross-app page redirection from a web page is abnormal?

Symptom

After users tap a link on the chat screen of a social app to access a web page, an exception occurs when the users attempt to switch from web page A of the app to web page B of another app. For example, an exception occurs when the users switch from the broadband recharge page of app A to the payment page of app B.

Possible Causes

  1. The UA of web page B does not adapt to HarmonyOS devices or browser environments, resulting in compatibility issues.
  2. Resources on web page B fail to load.

Solution

  1. Adapt the UA. Ensure that web page B adapts to the UA of HarmonyOS devices and the accompanying browser to correctly identify the device and redirect to the corresponding page or platform. For details, see Developing User-Agent.
  2. Check the resource loading of web page B.

[h2]What should I do if an exception occurs during app redirection from a web page?

Symptom

After users tap a link on the chat screen of a social app to access a web page, an exception occurs when the users attempt to switch from the web page to an app. Example:

  1. The Open button does not respond.
  2. After the Download button is tapped, the users are redirected to an incorrect platform or prompted to directly download an APK package.

Possible Causes

  1. For no response from the Open button: The target app is not correctly configured with the redirection logic (for example, App Linking), or there are errors in the configuration process.
  2. For no response from the Open button: The web page uses an incorrect link for the Open button.
  3. For errors from the Download button: The web page does not correctly adapt to the UA of HarmonyOS devices.

Solution

Sample Code