鸿蒙学习实战之路-Share Kit系列(6/17)-分享链接内容实战

最近好多朋友问我:“西兰花啊,我想让用户分享链接,比如商品链接、文章链接之类的,但不知道代码怎么写?” 害,这问题可问对人了!

今天这篇,我就手把手带你实现分享链接功能,从零到一,全程不超过 5 分钟(不含调试时间)~


分享链接是啥?

分享链接就是把一个 URL 链接分享到其他应用或设备。比如:

  • 分享商品链接到微信
  • 分享文章链接到微博
  • 分享网页链接到浏览器

Share Kit 支持两种类型的链接:

  1. App Linking:直达应用内的指定页面
  2. 普通链接:直达浏览器

App Linking vs 普通链接

App Linking

App Linking 是一种特殊的链接,可以直达应用内的指定页面。比如,用户点击链接后,会直接打开你的应用,并跳转到指定的页面。

这就像前端的 Deep Link,但更强大的是,App Linking 是系统级别的服务,体验更统一。

使用场景

  • 分享商品详情页链接
  • 分享文章详情页链接
  • 分享活动页面链接

普通链接

普通链接是指非 App Linking 的链接,会直达浏览器。比如,用户点击链接后,会直接打开浏览器,并跳转到指定的网页。

使用场景

  • 分享网页链接
  • 分享第三方网站链接
  • 分享 H5 页面链接

分享 App Linking

完整代码示例

import { common } from '@kit.AbilityKit';
import { appLinking } from '@kit.AppLinkingKit';
import { systemShare } from '@kit.ShareKit';

// 步骤1:构造App Linking
let appLinking: appLinking.AppLinking = appLinking.createAppLinking({
  packageName: 'com.example.app',
  path: '/pages/detail',
  parameters: {
    id: '123'
  }
});

// 步骤2:构造分享数据
let shareData: systemShare.SharedData = new systemShare.SharedData({
  utd: 'general.link',
  uri: appLinking.getUri(),
  title: '分享App Linking',
  preview: 'file://.../preview.jpg',
  description: '这是一个分享App Linking'
});

// 步骤3:构建分享控制器
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);

// 步骤4:显示分享面板
let uiContext: UIContext = this.getUIContext();
let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;

controller.show(context, {
  previewMode: systemShare.SharePreviewMode.DEFAULT,
  selectionMode: systemShare.SelectionMode.SINGLE
});

参数详解

packageName - 应用包名

packageName: 'com.example.app' 是目标应用的包名。

这个包名需要和你的应用包名一致,否则 App Linking 无法生效。

path - 页面路径

path: '/pages/detail' 是目标应用的页面路径。

这个路径需要和你的应用页面路径一致,否则无法跳转到正确的页面。

parameters - 页面参数

parameters: { id: '123' } 是目标应用的页面参数。

这些参数会传递到目标页面,方便页面获取数据。


分享普通链接

完整代码示例

import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';

// 步骤1:构造分享数据
let shareData: systemShare.SharedData = new systemShare.SharedData({
  utd: 'general.link',
  uri: 'https://www.example.com',
  title: '分享普通链接',
  preview: 'file://.../preview.jpg',
  description: '这是一个分享普通链接'
});

// 步骤2:构建分享控制器
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);

// 步骤3:显示分享面板
let uiContext: UIContext = this.getUIContext();
let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;

controller.show(context, {
  previewMode: systemShare.SharePreviewMode.DEFAULT,
  selectionMode: systemShare.SelectionMode.SINGLE
});

参数详解

uri - 链接地址

uri: 'https://www.example.com' 是要分享的链接地址。

这个链接需要是合法的 URL 格式,否则分享会失败。

🥦 西兰花警告
我有个朋友第一次分享链接,随便写了个字符串,结果分享面板弹出来但分享失败,debug 了两小时才发现不是合法的 URL!血泪教训啊朋友们!


在实际项目中怎么用?

上面的代码是基础实现,但在实际项目中,你可能会这样用:

示例:分享商品链接

import { common } from '@kit.AbilityKit';
import { appLinking } from '@kit.AppLinkingKit';
import { systemShare } from '@kit.ShareKit';

@Entry
@Component
struct ProductPage {
  // 商品数据
  productName: string = '西兰花';
  productId: string = '123';
  productImage: string = 'file://.../broccoli.jpg';
  productDescription: string = '新鲜西兰花,营养丰富,口感清脆';

  // 分享商品链接
  onShareProductLink() {
    // 构造App Linking
    let appLinking: appLinking.AppLinking = appLinking.createAppLinking({
      packageName: 'com.example.app',
      path: '/pages/product/detail',
      parameters: {
        id: this.productId
      }
    });

    // 构造分享数据
    let shareData: systemShare.SharedData = new systemShare.SharedData({
      utd: 'general.link',
      uri: appLinking.getUri(),
      title: this.productName,
      preview: this.productImage,
      description: this.productDescription
    });

    // 构建分享控制器
    let controller: systemShare.ShareController = new systemShare.ShareController(shareData);

    // 显示分享面板
    let uiContext: UIContext = this.getUIContext();
    let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;

    controller.show(context, {
      previewMode: systemShare.SharePreviewMode.DEFAULT,
      selectionMode: systemShare.SelectionMode.SINGLE
    });
  }

  build() {
    Column() {
      Image(this.productImage)
        .width(200)
        .height(200)
        .margin(20);

      Text(this.productName)
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ left: 20, right: 20, bottom: 10 })
        .fontColor(Color.Black);

      Text(this.productDescription)
        .fontSize(16)
        .margin({ left: 20, right: 20, bottom: 20 })
        .fontColor(Color.Gray);

      Button('分享商品链接')
        .onClick(() => {
          this.onShareProductLink();
        })
        .margin(20);
    }
    .width('100%')
    .height('100%');
  }
}

示例:分享网页链接

import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';

@Entry
@Component
struct WebPage {
  // 网页数据
  webTitle: string = '西兰花的营养价值';
  webUrl: string = 'https://www.example.com/article/broccoli-nutrition';
  webImage: string = 'file://.../preview.jpg';
  webDescription: string = '西兰花是一种营养丰富的蔬菜,富含维生素C、维生素K、膳食纤维等。';

  // 分享网页链接
  onShareWebLink() {
    // 构造分享数据
    let shareData: systemShare.SharedData = new systemShare.SharedData({
      utd: 'general.link',
      uri: this.webUrl,
      title: this.webTitle,
      preview: this.webImage,
      description: this.webDescription
    });

    // 构建分享控制器
    let controller: systemShare.ShareController = new systemShare.ShareController(shareData);

    // 显示分享面板
    let uiContext: UIContext = this.getUIContext();
    let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;

    controller.show(context, {
      previewMode: systemShare.SharePreviewMode.DEFAULT,
      selectionMode: systemShare.SelectionMode.SINGLE
    });
  }

  build() {
    Column() {
      Image(this.webImage)
        .width(200)
        .height(200)
        .margin(20);

      Text(this.webTitle)
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ left: 20, right: 20, bottom: 10 })
        .fontColor(Color.Black);

      Text(this.webDescription)
        .fontSize(16)
        .margin({ left: 20, right: 20, bottom: 20 })
        .fontColor(Color.Gray);

      Button('分享网页链接')
        .onClick(() => {
          this.onShareWebLink();
        })
        .margin(20);
    }
    .width('100%')
    .height('100%');
  }
}

App Linking 如何配置?

上面的代码中,我们构造了 App Linking,但要让 App Linking 生效,还需要在目标应用中进行配置。

配置步骤

  1. 在 module.json5 中声明技能
{
  "module": {
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "startWindowIcon": "$media:launcher",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "ohos.want.action.viewData"
            ],
            "uris": [
              {
                "scheme": "https",
                "host": "www.example.com",
                "path": "/pages/product/detail"
              }
            ]
          }
        ]
      }
    ]
  }
}
  1. 在页面中获取参数
import { router } from '@kit.ArkUI';

@Entry
@Component
struct ProductDetailPage {
  aboutToAppear() {
    // 获取页面参数
    let params = router.getParams() as Record<string, string>;
    let productId = params['id'];

    console.log(`商品ID:${productId}`);
  }

  build() {
    Text('商品详情页')
      .fontSize(20)
      .margin(20);
  }
}

🥦 西兰花小贴士
App Linking 的配置比较复杂,需要仔细配置 module.json5 中的 skills 和 uris。如果配置不正确,App Linking 无法生效。


常见问题

Q1:分享链接时提示"链接无效"怎么办?

检查以下几点:

  1. 链接格式是否正确

    • 确认 uri 是否为合法的 URL 格式
    • 确认 uri 是否以 http://https:// 开头
  2. App Linking 配置是否正确

    • 确认 module.json5 中的 skills 和 uris 配置是否正确
    • 确认 packageName 和 path 是否和目标应用一致

Q2:App Linking 和普通链接有什么区别?

特性 App Linking 普通链接
跳转目标 应用内指定页面 浏览器
用户体验 更好,直达应用 一般,需要打开浏览器
配置复杂度 复杂,需要配置 简单,直接分享
适用场景 分享应用内内容 分享网页内容

Q3:如何判断链接是 App Linking 还是普通链接?

可以通过链接的 scheme 来判断:

  • App Linking:scheme 通常是自定义的,比如 myapp://
  • 普通链接:scheme 是 http://https://

下一步学什么?

看完这篇,你应该已经能实现分享链接功能了。接下来可以深入学习:

  1. 高级功能:自定义分享面板、获取分享结果
  2. 共享联系人到推荐区:让分享更精准
  3. 目标应用接入:让你的应用能接收其他应用分享的链接
  4. 跨端分享:碰一碰分享、隔空传送

推荐资料

📚 官方文档


我是盐焗西兰花,
不教理论,只给你能跑的代码和避坑指南。
下期见!🥦

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐