HarmonyOS 鸿蒙Next中怎么在应用里拉起小红书App?

HarmonyOS 鸿蒙Next中怎么在应用里拉起小红书App? 请给出可用的示例代码,谢谢。

4 回复

【解决方案】

deep link基于隐式Want机制匹配中的uri匹配来查询拉起目标应用,首先在entry模块中的module.json5文件中配置querySchemes属性,声明想要查询的URL Scheme。

{
  "module": {
    ...
    "querySchemes": [
      // 小红书
      'xhsdiscover'
    ]
  }
}

使用bundleManager.canOpenlink判断目标URL Scheme对应应用是否可以访问,可以访问则通过UIAbilityContext.openLink拉起目标应用。

import { BusinessError } from '@kit.BasicServicesKit';
import { bundleManager, common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

class SchemeModel {
  appName: string = '';
  scheme: string = '';
  domain?: string = '';
  path?: string = '';

  constructor(appName: string, scheme: string, domain: string = 'home', path: string = '') {
    this.appName = appName;
    this.scheme = scheme;
    this.domain = domain;
    this.path = path;
  }

  getDeepLinking() {
    return this.path ? `${this.scheme}://${this.domain}/${this.path}` : `${this.scheme}://${this.domain}`
  }
}

@Entry
@Component
struct Index {
  @State curIndex: number = 0;
  schemeModels: SchemeModel[] = [
    new SchemeModel('小红书', 'xhsdiscover'),
  ];
  appNames: string[] = []

  aboutToAppear(): void {
    this.appNames = this.schemeModels.flatMap(schemeModel => schemeModel.appName);
  }

  build() {
    Column({ space: 20 }) {
      TextPicker({ range: this.appNames, selected: $$this.curIndex })
        .onChange((value: string | string[], index: number | number[]) => {
          hilog.info(0x0000, 'Testlog', `Picker item changed, value: : ${value}, index:  ${index}`);
        })
        .onScrollStop((value: string | string[], index: number | number[]) => {
          hilog.info(0x0000, 'Testlog', `Picker scroll stopped, value: : ${value}, index:  ${index}`);
        })

      Button('跳转')
        .width(200)
        .height(50)
        .onClick(() => {
          let link: string = this.schemeModels[this.curIndex].getDeepLinking();
          hilog.info(0x0000, 'Testlog', `link: ${link}`);
          try {
            let data = bundleManager.canOpenLink(link);
            if (data) {
              let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
              // 仅以App Linking的方式打开应用
              context.openLink(link, { appLinkingOnly: false }, (err, result) => {
                hilog.error(0x0000, 'Testlog', `openLink callback error code:${err.code}, error message:${err.message}`);
                hilog.info(0x0000, 'Testlog', `openLink callback result: ${JSON.stringify(result.resultCode)}`);
                hilog.info(0x0000, 'Testlog', `openLink callback result data: ${JSON.stringify(result.want)}`);
              })
                .then(() => {
                  hilog.info(0x0000, 'Testlog', 'openlink success.');
                })
                .catch((error: BusinessError) => {
                  promptAction.openToast({ message: `打开失败: ${error.name}` })
                  hilog.error(0x0000, 'Testlog', `openlink failed. error code:${error.code}, error message:${error.message}`);
                });
            } else {
              promptAction.openToast({ message: `暂无可用打开方式` })
            }
            hilog.info(0x0000, 'testTag', 'canOpenLink successfully: %{public}s', data);
          } catch (err) {
            let message = (err as BusinessError).message;
            promptAction.openToast({ message: `打开失败: ${message}` })
            hilog.error(0x0000, 'testTag', 'canOpenLink failed: %{public}s', message);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next中怎么在应用里拉起小红书App?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


研究了下它的 applinking ,以App Linking的方式打开应用

https://oia.xiaohongshu.com/.well-known/applinking.json

const context = this.getUIContext().getHostContext() as common.UIAbilityContext
const link: string = "https://oia.xiaohongshu.com/oia";
// 以App Linking的方式打开应用
context.openLink(link, { appLinkingOnly: false })
  .then(() => {
    console.info('openlink success.');
  })
const xhsUrlScheme = 'xhsdiscover://'
const canOpenXHS = bundleManager.canOpenLink(xhsUrlScheme)
if(canOpenXHS){
  let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
  context.openLink(xhsUrlScheme)
} else {
  toast('未安装小红书App,请安装后重试')
}

在module.json5里添加 querySchemes 配置:

"querySchemes": ["xhsdiscover"]

在HarmonyOS Next中,可以通过隐式意图(Implicit Intent)拉起第三方应用如小红书。以下是示例代码:

import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';

let context: common.UIAbilityContext = ... // 获取当前Ability的Context

try {
  let want = {
    action: 'ohos.want.action.viewData',
    entities: ['entity.system.browsable'],
    uri: 'xiaohongshu://' // 小红书的标准Deep Link协议
  };
  
  context.startAbility(want).then(() => {
    console.info('Succeeded in starting ability.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to start ability. Code: ${err.code}, message: ${err.message}`);
  });
} catch (error) {
  console.error(`An error occurred. Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
}

注意事项:

  1. 需要确认小红书在设备上已安装且支持xiaohongshu://协议
  2. 可在应用的module.json5中声明需要的权限:
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.START_ABILITIES_FROM_BACKGROUND"
      }
    ]
  }
}
  1. 实际协议可能因小红书版本更新而变化,建议查阅小红书官方开放平台文档,
回到顶部