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:
App Linking supports three typical redirection scenarios and intelligently routes users based on their device status.
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.
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.
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.
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.
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:
Create an associated website domain name for your app in AppGallery Connect.
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
}
]
}
],
// ...
}
} Verify the app launch effect.
Manually sign your app.
Compile and package the app, and install it on the debugging device.
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.
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}`);
}
}
// ...
} When a user taps the shared link to launch the app, the article details page is displayed in either of the following scenarios:
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}`);
}
});
} 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}`);
});
}
}
} 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);
}
}
// ...
} To improve user experience when the app is not installed, you can configure the function of direct access to AppGallery to guide users to download and install the app.
In App Linking of AppGallery Connect, enable the function of direct access to AppGallery.
After the configuration is complete, when a user taps the App Linking link shared in MeeTime, if the target app is not installed on the device, the system directly redirects the user to the app details page on AppGallery, where the user can download and install the app with just one tap.
In addition, you need to implement the deferred link function to ensure that users can directly access the content when they launch the app for the first time after installation.
After the app is installed, you can use the deferred link to directly 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 link conversion rate.
Call the deferredLink.popDeferredLink() API to obtain the original link of App Linking and redirect the user to the 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}`);
});
}
// ...
} 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:
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:
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.
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
Solution
// 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
}
]
}
],
// ...
}
} Symptom
After a user taps a link in a social app, the web page cannot be displayed properly in the browser. For example, the web page is blank, the interaction is abnormal, or the page loading is abnormal.
Possible causes
Solution
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
Solution
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:
Possible causes
Solution