HarmonyOS 鸿蒙Next中canOpenLink与openLink组合使用问题

HarmonyOS 鸿蒙Next中canOpenLink与openLink组合使用问题

import { bundleManager } from '@kit.AbilityKit';

try {

  let link = 'appScheme://host/path';

  let canOpen = bundleManager.canOpenLink(link);

} catch (err) {

  console.error(`Error code: ${err.code}, Message: ${err.message}`);

}

canOpenLink 中的scheme不能是https,但是openLink文档中scheme必须配置为https,canOpenLink 与 openLink 应该怎么组合使用?


更多关于HarmonyOS 鸿蒙Next中canOpenLink与openLink组合使用问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

开发者您好,openLink通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须同时具备以下过滤器特征,才能处理App Linking链接:

  • “actions"列表中包含"ohos.want.action.viewData”。
  • “entities"列表中包含"entity.system.browsable”。
  • "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。

 不是openLink中link参数必须包含"https", 只是处理App Linking链接才有如上限制。

canOpenLink 与 openLink是可以配置使用的。可以参考如下案例:

  1. 在module.json5文件中增加querySchemes字段,并在列表中配置"huaweischeme"。

"huaweischeme"为需要跳转到的运动健康App首页的scheme,示例如下:

  "module": {
    "querySchemes": [
      "huaweischeme"
    ]
  }
  1. 完整代码如下:
import { bundleManager, common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { productViewManager } from '@kit.AppGalleryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct PrivacyAuthDemo {
  build() {
    Button('跳转链接')
      .onClick(async () => {
        try {
          let result = bundleManager.canOpenLink('huaweischeme://healthapp/home/main');
          let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
          if (result) {
            // 拉起运动健康App首页,进行隐私授权
            let link: string = 'huaweischeme://healthapp/home/main';
            await context.openLink(link);
          } else {
            // 拉起应用市场推荐,引导用户下载运动健康App,进行隐私授权
            const wantParam: Want = {
              parameters: {
                bundleName: 'com.huawei.hmos.health'
              }
            };
            const callback: productViewManager.ProductViewCallback = {
              onError: (error: BusinessError) => {
                hilog.error(0x0001, 'TAG', `Failed to open AppGallery.Code: ${error.code}, message: ${error.message}`);
              }
            };
            productViewManager.loadProduct(context, wantParam, callback);
          }
        } catch (err) {
          hilog.error(0x0000, 'testTag', `Failed to agree user privacy.Code: ${err.code}, message: ${err.message}`);
        }
      });
  }
}

更多关于HarmonyOS 鸿蒙Next中canOpenLink与openLink组合使用问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


试下这个demo呢

import { bundleManager, common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct PrivacyAuthDemo {
  build() {
    Button('点击一下')
      .onClick(async () => {
        try {
          // 1. 地图是否安装
          const scheme = 'maps://navigation';
          const canOpen = bundleManager.canOpenLink(scheme);
          const context = this.getUIContext().getHostContext() as common.UIAbilityContext;

          if (canOpen) {
            // 2. 已安装:拉起地图App
            await context.openLink(scheme);
          }
        } catch (err) {
          hilog.error(0x0000, 'AuthError', `拉起失败: ${JSON.stringify(err)}`);
        }
      });
  }
}

module.json5配置下:

    "querySchemes": [
      "maps"
    ],

在HarmonyOS Next中,canOpenLink用于检查能否打开指定链接,返回布尔值;openLink用于直接打开链接。组合使用时,应先调用canOpenLink进行判断,确认可打开后再调用openLink执行操作。这能避免因链接无效或环境不支持导致的打开失败。

在HarmonyOS Next中,canOpenLinkopenLink的组合使用遵循以下逻辑:

  1. 功能定位

    • canOpenLink:用于检测设备上是否有能处理特定URI Scheme的应用。它检查的是应用声明的Scheme能力,不涉及具体网络协议。
    • openLink:用于实际拉起对应应用,并传递数据。其文档要求配置https,是指应用需要在module.json5中声明skillsschemes字段包含https,以表明自己能处理网页链接。
  2. 组合使用方式

    • 对于应用自定义Scheme(如appScheme://),先用canOpenLink检测应用是否存在,再用openLink拉起。
    • 对于网页链接https://),通常不需要调用canOpenLink,因为系统默认浏览器总是可用。直接调用openLink即可。
  3. 代码示例

    import { bundleManager, common } from '[@kit](/user/kit).AbilityKit';
    
    // 场景1:检测并拉起自定义Scheme应用
    let customLink = 'appScheme://host/path';
    try {
      let canOpen = bundleManager.canOpenLink(customLink);
      if (canOpen) {
        common.openLink(customLink); // 安全拉起
      } else {
        console.log('未找到处理该Scheme的应用');
      }
    } catch (err) {
      console.error(`Error: ${err.code}, ${err.message}`);
    }
    
    // 场景2:直接打开网页链接
    let webLink = 'https://developer.harmonyos.com';
    try {
      common.openLink(webLink); // 直接调用,系统会使用浏览器打开
    } catch (err) {
      console.error(`Error: ${err.code}, ${err.message}`);
    }
    
  4. 关键区别

    • canOpenLink的Scheme参数用于匹配应用声明的Scheme,不是网络协议。
    • openLinkhttps配置要求是应用声明的一部分,确保应用能被识别为网页处理器。

总结:检测自定义Scheme用canOpenLink,打开网页直接调用openLink,两者根据场景配合使用。

回到顶部