找回密码
 立即注册
首页 业界区 业界 鸿蒙应用开发UI基础第七节:DeepLinking与AppLinking应 ...

鸿蒙应用开发UI基础第七节:DeepLinking与AppLinking应用链接实战——跨应用跳转

任静柔 3 天前
【学习目标】


  • 理解应用链接的核心作用,掌握其解耦跨应用跳转的实现逻辑;
  • 完成 Deep Linking 全流程开发:自定义Scheme配置、canOpenLink校验后拉起、Web组件拦截跳转、参数解析;
  • 完成 App Linking 全流程开发:AGC云端配置、服务器配置、客户端配置、拉起与降级处理、校验验证;
  • 掌握 canOpenLink 跳转前置校验的使用方式、配置要求与版本限制;
  • 能根据业务场景合理选择 Deep Linking 或 App Linking 完成落地开发。
【内容铺垫】

上一节我们掌握了 显式 Want / 隐式 Want 拉起组件的核心原理,其中隐式 Want 已能通过特征匹配实现跨应用跳转,但实际项目中更常用标准化 URI 链接统一跳转逻辑:

  • Deep Linking:基于隐式Want URI匹配,自定义Scheme,适合内部/测试场景;
  • App Linking:在Deep Linking基础上增加域名校验,支持未安装降级打开网页,适合对外发布场景。
说明:隐式 Want使用方法匹配规则上节已讲透,本节不再演示隐式相关代码,只聚焦生产环境中更实用的「链接式跳转+前置校验」全流程实战。
本节复用第六节的 WantAndLinkingDemo(调用方)和 ImplicitReceiverDemo(接收方)工程,无需新增额外工程结构。
一、应用链接核心概念

应用链接通过标准化 URI 规则匹配并拉起目标应用,核心分为两种类型:
1. 两种应用链接对比

维度Deep LinkingApp Linking实现原理隐式Want URI匹配Deep Linking + 域名校验协议格式自定义Scheme标准 HTTPS 域名配置范围仅客户端本地配置云端 + 服务器 + 客户端未安装应用处理直接跳转失败自动降级打开网页canOpenLink 支持支持不支持适用场景内部跳转、调试、轻量场景分享、扫码、广告、对外发布2. 通用开发规则


  • 被拉起的目标组件必须配置 exported: true,否则普通应用无法触发跳转;
  • 应用链接规则需配置在独立的skill对象中,不可与桌面入口skill(entities: ["entity.system.home"])混用;
  • skills 配置中 actions 字段不能为空,否则链接匹配会直接失败;
  • 使用 canOpenLink 前,调用方需在 entry/module.json5 配置 querySchemes 声明待校验的Scheme:

    • API 21 及以上版本:最多配置 200 个 Scheme;
    • API 20 及以下版本:最多配置 50 个 Scheme。

二、工程结构(仅展示新增/修改部分)
  1. # 调用方:WantAndLinkingDemo
  2. WantAndLinkingDemo/
  3. ├─ entry/src/main/ets/entryability/EntryAbility.ets    // 仅负责页面加载,无额外修改
  4. ├─ entry/src/main/ets/pages/Index.ets                  // 新增Linking演示入口按钮
  5. ├─ entry/src/main/ets/pages/LinkingPage.ets            // 核心:链接拉起+校验演示
  6. ├─ entry/src/main/resources/rawfile/index.html         // Web组件跳转测试页面
  7. └─ entry/src/main/module.json5                         // 新增querySchemes配置
  8. # 接收方:ImplicitReceiverDemo
  9. ImplicitReceiverDemo/
  10. ├─ entry/src/main/ets/entryability/EntryAbility.ets    // 新增链接参数解析逻辑
  11. ├─ entry/src/main/ets/pages/Index.ets                  // 新增参数展示区域
  12. └─ entry/src/main/module.json5                         // 新增Deep/App Linking skill配置
复制代码
三、Deep Linking 实战(自定义Scheme+前置校验)

(一)接收方:ImplicitReceiverDemo 配置与参数解析

1. module.json5 配置Deep Linking独立skill
  1. {
  2.   "module": {
  3.     "abilities": [
  4.       {
  5.         "exported": true, // 必须开启,否则无法被外部应用拉起
  6.         "skills": [
  7.           // 配置 Deep Linking
  8.           {
  9.             "actions": ["ohos.want.action.viewData"], // 不能为空
  10.             "uris": [
  11.               {
  12.                 "scheme": "harmonydemo", // 自定义Scheme,不以ohos开头
  13.                 "host": "www.example.com",
  14.                 "pathStartWith": "programs" // 匹配路径前缀
  15.               }
  16.             ]
  17.           }
  18.         ]
  19.       }
  20.     ]
  21.   }
  22. }
复制代码
2. EntryAbility.ets 解析链接参数
  1. import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
  2. import { url } from '@kit.ArkTS';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { window } from '@kit.ArkUI';
  5. const DOMAIN = 0x0000;
  6. const TAG = 'ImplicitReceiverDemo';
  7. export default class EntryAbility extends UIAbility {
  8.   // 应用首次启动时解析参数
  9.   onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  10.     this.parseLinkParams(want);
  11.   }
  12.   // 应用已启动,再次被拉起时更新参数
  13.   onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  14.     this.parseLinkParams(want);
  15.   }
  16.   onWindowStageCreate(windowStage: window.WindowStage): void {
  17.     windowStage.loadContent('pages/Index');
  18.   }
  19.   // 统一解析Deep Linking参数(替换id为linkId)
  20.   private parseLinkParams(want: Want) {
  21.     const uri = want.uri;
  22.     if (!uri) return;
  23.     try {
  24.       // 官方标准URI解析方式
  25.       const urlObject = url.URL.parseURL(uri);
  26.       const action = urlObject.params.get('action');
  27.       const linkId = urlObject.params.get('linkId');
  28.       
  29.       // 存入AppStorage供页面展示
  30.       AppStorage.setOrCreate('action', action || '');
  31.       AppStorage.setOrCreate('linkId', linkId || '');
  32.       hilog.info(DOMAIN, TAG, `参数解析成功:action=${action}, linkId=${linkId}`);
  33.     } catch (err) {
  34.       hilog.error(DOMAIN, TAG, `参数解析失败:${JSON.stringify(err)}`);
  35.     }
  36.   }
  37. }
复制代码
3. Index.ets 展示解析后的参数
  1. @Entry
  2. @Component
  3. struct Index {
  4.   // 绑定AppStorage中的参数
  5.   @StorageProp('action') action: string = '';
  6.   @StorageProp('linkId') linkId: string = '';
  7.   build() {
  8.     Column({ space: 20}) {
  9.       Text('Deep Linking 接收页面')
  10.         .fontSize(32)
  11.         .fontWeight(FontWeight.Bold);
  12.       
  13.       Text(`解析action参数:${this.action}`)
  14.         .fontSize(18)
  15.         .fontColor(Color.Blue)
  16.         .padding(10)
  17.         .backgroundColor('#f0f7ff');
  18.       
  19.       Text(`解析linkId参数:${this.linkId}`)
  20.         .fontSize(18)
  21.         .fontColor(Color.Green)
  22.         .padding(10)
  23.         .backgroundColor('#e6fffa');
  24.     }
  25.     .width('100%')
  26.     .height('100%')
  27.     .justifyContent(FlexAlign.Center)
  28.     .padding(20);
  29.   }
  30. }
复制代码
(二)调用方:WantAndLinkingDemo 实现校验+拉起逻辑

1. rawfile/index.html(Web组件跳转测试页面)
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7.     <title>Deep Linking H5跳转演示</title>
  8.    
  9. </head>
  10. <body>
  11. <h1>Deep Linking Web组件跳转演示</h1>
  12.     <button onclick="jump()">按钮跳转Deep Linking</button>
  13.     超链接跳转Deep Linking
  14. </body>
  15. </html>
复制代码
2. LinkingPage.ets(核心:校验后拉起+Web组件拦截)
  1. import { bundleManager, common } from '@kit.AbilityKit';
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { promptAction } from '@kit.ArkUI';
  5. import { webview } from '@kit.ArkWeb';
  6. const TAG = 'LinkingPage';
  7. const DOMAIN = 0x0000;
  8. // Deep Linking链接
  9. const DEEP_LINK = 'harmonydemo://www.example.com/programs?action=showall&linkId=10086';
  10. // App Linking链接(需替换为自己的已校验域名)
  11. const APP_LINK = 'https://www.example.com/programs?action=showall&linkId=10086';
  12. @Entry
  13. @Component
  14. struct LinkingPage {
  15.   private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
  16.   private webController = new webview.WebviewController();
  17.   build() {
  18.     Column({ space: 15}) {
  19.       Text('应用链接实战')
  20.         .fontSize(30)
  21.         .fontWeight(FontWeight.Bold)
  22.         .margin({ bottom: 10 });
  23.       // 1. canOpenLink校验后拉起
  24.       Button('1. 校验后拉起Deep Linking')
  25.         .width('80%')
  26.         .height(50)
  27.         .backgroundColor('#40a9ff')
  28.         .fontColor($r('sys.color.white'))
  29.         .onClick(() => this.checkAndOpenDeepLink());
  30.       // 2. Web组件内拦截跳转
  31.       Text('2. Web组件内跳转Deep Linking')
  32.         .fontSize(20)
  33.         .margin({ top: 20, bottom: 10 });
  34.       Web({ src: $rawfile('index.html'), controller: this.webController })
  35.         .width('100%')
  36.         .height(200)
  37.         .onLoadIntercept((event) => {
  38.           const url = event.data.getRequestUrl();
  39.           // 拦截自定义Scheme链接
  40.           if (url.startsWith('harmonydemo://')) {
  41.             this.checkAndOpenDeepLink(); // 复用校验逻辑,保证体验一致
  42.             return true; // 阻止Web组件加载该链接
  43.           }
  44.           return false; // 允许加载其他普通链接
  45.         });
  46.       // --- App Linking 演示区域 ---
  47.       Text('App Linking 拉起演示')
  48.         .fontSize(20)
  49.         .margin({ top: 30, bottom: 10 });
  50.       Button('3. App Linking仅应用拉起')
  51.         .width('80%')
  52.         .height(50)
  53.         .backgroundColor('#722ed1')
  54.         .fontColor($r('sys.color.white'))
  55.         .onClick(() => this.openAppLinkOnly());
  56.       Button('4. App Linking优先应用+降级')
  57.         .width('80%')
  58.         .height(50)
  59.         .backgroundColor('#722ed1')
  60.         .fontColor($r('sys.color.white'))
  61.         .onClick(() => this.openAppLinkPriority());
  62.     }
  63.     .width('100%')
  64.     .height('100%')
  65.     .justifyContent(FlexAlign.Center)
  66.     .backgroundColor('#f5f5f5')
  67.     .padding(20);
  68.   }
  69.   // 核心方法:校验后拉起Deep Linking
  70.   private  checkAndOpenDeepLink() {
  71.     try {
  72.       // 前置校验:判断是否有应用可处理该链接
  73.       const canOpen =  bundleManager.canOpenLink(DEEP_LINK);
  74.       hilog.info(DOMAIN, TAG, `canOpenLink校验结果:${canOpen}`);
  75.       if (canOpen) {
  76.         // 校验通过,执行拉起
  77.        this.context.openLink(DEEP_LINK, { appLinkingOnly: false });
  78.         hilog.info(DOMAIN, TAG, 'Deep Linking拉起成功');
  79.       } else {
  80.         promptAction.showToast({ message: '暂无应用可处理该链接' });
  81.       }
  82.     } catch (err) {
  83.       const error = err as BusinessError;
  84.       hilog.error(DOMAIN, TAG, `拉起失败:${error.code}-${error.message}`);
  85.       promptAction.showToast({ message: '链接拉起失败' });
  86.     }
  87.   }
  88.   // App Linking仅应用拉起(无匹配应用则抛异常)
  89.   private async openAppLinkOnly() {
  90.     try {
  91.       await this.context.openLink(APP_LINK, { appLinkingOnly: true });
  92.       hilog.info(DOMAIN, TAG, 'App Linking仅应用方式拉起成功');
  93.     } catch (err) {
  94.       const error = err as BusinessError;
  95.       hilog.error(DOMAIN, TAG, `仅应用拉起失败:${error.code}-${error.message}`);
  96.       promptAction.showToast({ message: '无匹配应用,拉起失败' });
  97.     }
  98.   }
  99.   // App Linking优先应用拉起(无应用则打开网页)
  100.   private async openAppLinkPriority() {
  101.     try {
  102.       await this.context.openLink(APP_LINK, { appLinkingOnly: false });
  103.       hilog.info(DOMAIN, TAG, 'App Linking优先应用方式拉起成功');
  104.     } catch (err) {
  105.       const error = err as BusinessError;
  106.       hilog.error(DOMAIN, TAG, `优先应用拉起失败:${error.code}-${error.message}`);
  107.       promptAction.showToast({ message: '应用未安装,将打开网页版' });
  108.     }
  109.   }
  110. }
复制代码
3. 调用方module.json5配置
  1. {
  2.   "module": {
  3.     "querySchemes": ["harmonydemo"], // 声明待校验的Scheme,必须配置
  4.     "abilities": [
  5.       {
  6.         "name": "EntryAbility",
  7.         "exported": true,
  8.         "skills": [
  9.           {
  10.             "entities": ["entity.system.home"],
  11.             "actions": ["ohos.want.action.home"]
  12.           }
  13.         ]
  14.       }
  15.     ]
  16.   }
  17. }
复制代码
4. 调用方展示页Index.ets
  1. import router from '@ohos.router';
  2. @Entry
  3. @Component
  4. struct Index {
  5.   build() {
  6.     Column({ space: 10}) {
  7.       // 6.Linking演示
  8.       Button('6. Linking演示')
  9.         .width('80%')
  10.         .height(50)
  11.         .fontSize(18)
  12.         .backgroundColor('#1890ff')
  13.         .fontColor($r('sys.color.white'))
  14.         .onClick(() => {
  15.           router.push({ url:"pages/LinkingPage"})
  16.         });
  17.     }
  18.     .width('100%')
  19.     .height('100%')
  20.     .justifyContent(FlexAlign.Center);
  21.   }
  22. }
复制代码
5. DeepLinking演示效果

1.gif

四、App Linking 实战(HTTPS域名+域名校验)

App Linking在Deep Linking基础上增加了域名校验环节,通过域名校验可消除应用归属歧义,让链接更安全可靠。其核心特性是:同一HTTPS网址支持「应用+网页」双端呈现,应用已安装则打开应用,未安装则降级打开网页。
1. 前置准备


  • 已注册华为开发者账号并完成实名认证;
  • 已在AGC(AppGallery Connect)创建应用,且应用包名与本地工程一致;
  • 已准备好备案的HTTPS域名(如www.xxxx.com)及域名服务器部署权限;
  • 应用已配置手动签名(禁止使用DevEco Studio自动签名),新建AppID-开放能力-勾选App Linking。
2. 服务器配置(关键)

2.1 编写applinking.json文件

创建名为applinking.json的文件,内容如下(替换为自己的APP ID):
  1. {
  2. "applinking": {
  3.    "apps": [
  4.      {
  5.        "appIdentifier": "6917598487740171507"
  6.      }
  7.    ]
  8. }
  9. }
复制代码
同一个网站域名可以关联多个应用,只需要在"apps"列表里放置多个"appIdentifier"元素即可,其中每个"appIdentifier"元素对应每个应用。
2.2 部署applinking.json文件


  • 在域名服务器的根目录下创建.well-known文件夹(注意前缀有.);
  • 将applinking.json文件放入.well-known文件夹;
  • 确保文件可通过HTTPS访问:https://www.example.com/.well-known/applinking.json;
3. AGC云端配置(核心)

3.1 开通App Linking服务


  • 登录AGC控制台,选择目标应用;
  • 进入「增长 > App Linking > 应用链接」,点击「立即开通」;
  • 阅读并同意服务协议,完成服务开通。
3.2 配置关联域名


  • 在「应用链接」页面点击「添加域名」;
  • 输入已备案的HTTPS域名(如www.example.com),点击「下一步」;
2.png


  • 点击「发布」,此时 AGC会对该网站域名的配置文件所包含的应用与本项目内的应用列表进行交集校验。
3.3 AGC校验结果


  • 如果域名的配置文件中有应用存在本项目中,则发布成功,点击“查看”可显示该域名关联的应用信息。
  • 如果异步校验中,则状态为“发布中”。
  • 如果配置文件中没有任何应用在本项目中,则发布失败,点击“查看”可显示发布失败原因。
3.png

AGC校验更新每24小时更新一次
4. 客户端配置(接收方)

4.1 module.json5新增App Linking配置
  1. {
  2.   "module": {
  3.     "abilities": [
  4.       {
  5.         "name": "EntryAbility",
  6.         "exported": true,
  7.         "skills": [
  8.           // 桌面入口skill
  9.           {
  10.             "entities": ["entity.system.home"],
  11.             "actions": ["ohos.want.action.home"]
  12.           },
  13.           // Deep Linking配置(保留)
  14.           {
  15.             "actions": ["ohos.want.action.viewData"],
  16.             "uris": [
  17.               {
  18.                 "scheme": "harmonydemo",
  19.                 "host": "www.example.com",
  20.                 "pathStartWith": "programs"
  21.               }
  22.             ]
  23.           },
  24.           // App Linking独立配置(新增)
  25.           {
  26.             "entities": ["entity.system.browsable"], // 必须配置,标识可被浏览器唤起
  27.             "actions": ["ohos.want.action.viewData"], // 不能为空
  28.             "uris": [
  29.               {
  30.                 "scheme": "https", // 固定为https
  31.                 "host": "www.example.com", // 与AGC配置的域名一致
  32.                 // "path": "programs"  // path可选,表示域名服务器上的目录或文件路径,例如www.example.com/programs中的programs
  33.               }
  34.             ],
  35.             "domainVerify": true // 开启域名校验(核心)
  36.           }
  37.         ]
  38.       }
  39.     ]
  40.   }
  41. }
复制代码
4. 客户端处理传入的链接(接收方)
  1.   onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  2.     this.parseAppLinking(want)
  3.   }
  4.   /**
  5.    * AppLinking
  6.    * @param want 从want中获取传入的链接信息。
  7.    */
  8.   private parseAppLinking(want:Want){
  9.     // 假如传入的url为:https://www.example.com/programs?action=showall
  10.     let uri = want?.uri;
  11.     if (uri) {
  12.       // 从链接中解析query参数,拿到参数后,开发者可根据自己的业务需求进行后续的处理。
  13.       try {
  14.         let urlObject = url.URL.parseURL(want?.uri);
  15.         let action = urlObject.params.get('action');
  16.         // 例如,当action为showall时,展示所有的节目。
  17.         if (action === "showall"){
  18.           //...
  19.         }
  20.         //...
  21.       } catch (error) {
  22.         hilog.error(0x0000, 'testTag', `Failed to parse url.`);
  23.       }
  24.     }
  25.   }
复制代码
5.3 功能验证


  • 点击调用方「App Linking仅应用拉起」按钮:应用已安装则成功拉起,未安装则提示「无匹配应用」;
  • 点击「App Linking优先应用+降级」按钮:应用已安装则打开应用,未安装则自动打开浏览器访问https://www.example.com/programs?action=showall&linkId=10086。
五、避坑指南


  • Deep Linking匹配失败:检查skill是否独立配置、actions是否非空、Scheme/host是否匹配、exported是否为true;
  • canOpenLink校验失败:必须配置querySchemes,且Scheme与目标方完全一致;
  • Scheme命名规范:不能以ohos开头,不建议使用http/https/file等系统保留值;
  • 参数命名避坑:避免使用id等系统预留字段,建议使用linkId/bizId等业务自定义名称;
  • App Linking域名校验失败

    • 检查applinking.json路径是否为.well-known目录,且可通过HTTPS访问;
    • 检查appIdentifier是否与AGC中APP ID一致;
    • 检查设备网络是否正常,域名是否备案;
    • 应用必须手动签名,自动签名会导致校验失败;

六、内容总结


  • Deep Linking核心是自定义Scheme+隐式Want URI匹配,生产环境需结合canOpenLink前置校验后再拉起,避免跳转失败;
  • Web组件可通过onLoadIntercept拦截自定义Scheme链接,复用校验逻辑保证体验一致性;
  • App Linking需完成「AGC云端配置→服务器配置→客户端配置→验证」全流程,核心是域名校验,支持应用未安装时降级打开网页;
  • App Linking关键要求:备案的HTTPS域名、手动签名、applinking.json正确部署、domainVerify=true;
  • 应用链接配置核心规则:目标组件exported=true、链接规则独立skill配置、actions字段非空。
七、下节预告

本节我们完成了Deep Linking 与 App Linking 跨应用跳转的全流程实战,掌握了 canOpenLink 前置校验、openLink 同步拉起、Web 组件拦截、参数解析与降级处理等核心能力。
下一节我们将正式进入 ArkTS 声明式 UI 开发,学习页面标准结构、多设备尺寸适配、vp/fp 单位规范与 @State 数据驱动刷新,从零搭建可直接运行的鸿蒙 UI 页面,为后续布局与组件开发打下坚实基础。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册