鸿蒙Next开发分享功能Share Kit使用

716 阅读3分钟

Share Kit(分享服务)为应用提供文本、图片、视频等内容跨应用、跨端分享能力。

应用把需要分享的内容和预览样式配置给Share Kit,Share Kit将根据不同的场景进行使用:

  • 针对应用间分享的场景,根据分享的数据类型、数量等信息构建分享面板,为用户提供内容预览、推荐分享联系人、关联应用及操作界面,便于用户快速选择分享应用或操作,将内容分发到目标应用。
  • 针对跨端分享的场景,根据分享的数据类型、数量等信息构建预览界面,用于跨端分享。

为应对开发者接入系统分享能力时的不同诉求,Share Kit支持两种宿主应用接入模式。

接入模式接入方式&适用应用类型效果图
全接模式直接使用系统分享面板适用于华为自研应用以及对分享方式区无商业诉求的开发者,可直接使用系统面板,降低开发成本。直接使用系统分享面板
半接模式开发者自行开发分享能力面板,并在分享面板中提供系统分享入口适用于分享方式区有商业诉求,或有自己独有的业务逻辑的开发者左侧为自开发分享面板,同时提供系统分享入口,用户点击时调用系统分享面板
import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { fileUri } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import Logger from '../utils/Logger';

let logger = Logger.getLogger('[AccessModel]');

@Component
export default struct AccessModel {
  @State message: ResourceStr = $r('app.string.access_model_title');
  @State isSheetShow: boolean = false;

  private async handelShare(): Promise<void> {
    const contextFaker: Context = getContext(this);
    let filePath = contextFaker.filesDir + '/exampleImage.jpg';
    let utdTypeId = utd.getUniformDataTypeByFilenameExtension('.jpg', utd.UniformDataType.IMAGE);
    let shareData: systemShare.SharedData = new systemShare.SharedData({
      utd: utdTypeId,
      uri: fileUri.getUriFromPath(filePath),
      title: 'Picture Title',
      description: 'Picture Description',
    });
    let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
    let context = getContext(this) as common.UIAbilityContext;
    controller.show(context, {
      previewMode: systemShare.SharePreviewMode.DETAIL,
      selectionMode: systemShare.SelectionMode.BATCH,
    }).then(() => {
      console.info('HuaweiShare_ show');
    }).catch((error: BusinessError) => {
      console.error(`HuaweiShare_ show error. Code: ${error.code}, message: ${error.message}`);
    });
  }

  @Builder
  FullJoint() {
    Flex({ direction: FlexDirection.Row }) {
      Row() {
        Image($r('app.media.joint_full'))
          .width(100)
      }
      .width(150)
      .margin({ right: 12 })

      Column() {
        Flex({ direction: FlexDirection.Row }) {
          Text($r('app.string.full_title'))
            .flexGrow(1)
            .fontSize(20)
            .fontWeight(500)

          Button($r('app.string.share_btn'))
            .width(100)
            .height(30)
            .fontSize(14)
            .margin({ left: 8 })
            .onClick(() => this.handelShare())
        }.width('100%')

        Column() {
          Text($r('app.string.full_model'))
            .width('100%')
            .margin({ top: 12 })
            .fontWeight(500)
          Text($r('app.string.full_description'))
            .width('100%')
            .margin({ top: 12 })
        }.width('100%')
      }
      .flexGrow(1)
    }
    .margin({ bottom: 20 })
  }

  @Builder
  HalfJoint() {
    Flex({ direction: FlexDirection.Column }) {
      Column() {
        Flex({ direction: FlexDirection.Row }) {
          Text($r('app.string.half_title'))
            .flexGrow(1)
            .fontSize(20)
            .fontWeight(500)

          Button($r('app.string.share_btn'))
            .width(100)
            .height(30)
            .fontSize(14)
            .margin({ left: 8 })
            .bindSheet($$this.isSheetShow, this.HalfSheet(), {
              height: 220,
              title: this.HalfTitle(),
            })
            .onClick(() => {
              this.isSheetShow = true;
            })
        }.width('100%')

        Column() {
          Text($r('app.string.half_model'))
            .width('100%')
            .margin({ top: 12 })
            .fontWeight(500)
          Text($r('app.string.half_description'))
            .width('100%')
            .margin({ top: 12 })
        }.width('100%')
      }

      Row() {
        Image($r('app.media.joint_half'))
          .width(100)
          .margin({ left: 20 })

        Image($r('app.media.joint_full'))
          .width(100)
          .margin({ left: 20 })
      }
      .width('100%')
      .height(220)
      .margin({ top: 12 })
    }
    .margin({ bottom: 20 })
  }

  @Builder
  HalfTitle() {
    Text($r('app.string.share_to'))
      .fontSize(20)
      .fontWeight(500)
  }

  @Builder
  HalfSheet() {
    Flex({ direction: FlexDirection.Row }) {
      this.HalfAppItem();
      this.HalfAppItem();
      this.HalfAppItem();

      Column() {
        Column() {
          SymbolGlyph($r('sys.symbol.share'))
            .fontSize('24vp')
        }
        .width(48)
        .height(48)
        .borderRadius(12.4)
        .borderWidth($r('sys.float.border_small'))
        .borderColor('#99808080')
        .backgroundColor(Color.White)
        .justifyContent(FlexAlign.Center)

        Text($r('app.string.system_share'))
          .fontSize(12)
          .margin({ top: 8 })
      }
      .width('20%')
      .height(100)
      .justifyContent(FlexAlign.Center)
      .onClick(() => {
        this.handelShare();
      })
    }
    .width('100%')
    .height('100%')
    .padding({ left: 12, right: 12 })
  }

  @Builder
  HalfAppItem() {
    Column() {
      Image($r('app.media.app_icon'))
        .width(48)
        .height(48)

      Text($r('app.string.app'))
        .fontSize(12)
        .margin({ top: 8 })
    }
    .width('20%')
    .height(100)
    .justifyContent(FlexAlign.Center)
  }

  build() {
    Scroll() {
      Column() {
        Row() {
          Text(this.message)
            .fontSize(22)
            .fontWeight(FontWeight.Bold)
        }
        .width('100%')
        .margin({ bottom: 12 })

        this.FullJoint();

        this.HalfJoint();
      }
      .width('100%')
      .constraintSize({ minHeight: '100%' })
      .padding({ left: 20, right: 20 })
    }
    .width('100%')
    .height('100%')
  }
}

场景介绍

在手机设备中,分享框通过模态弹窗方式被拉起,效果如下图所示。

  1. 宿主应用可以分享一段文本、一个文件或一条备忘录到其他应用。
  2. 宿主应用可以分享多个内容,如文本、图片等到其他应用。

业务流程

流程说明:

1、宿主应用构造分享数据、构造ShareController以及注册分享面板状态监听(可选)。

2、宿主应用拉起系统分享面板。

3、用户可选择目标设备或者应用。

4、目标应用处理分享数据,并关闭系统分享面板。

设计规范

宿主应用接入系统分享时,根据不同的内容类型,应选择恰当的分享方式。详细参见:系统分享设计指南

接口说明

类名接口名描述
SharedDataconstructor(record: SharedRecord)SharedData构造函数
addRecord(record: SharedRecord): void添加分享记录
getRecords(): Array<SharedRecord>获取分享记录
ShareControllerconstructor(data: SharedData)ShareController构造函数
show(context: common.UIAbilityContext, options: ShareControllerOptions): Promise显示分享面板
on(event: 'dismiss', callback: () => void): void注册分享面板关闭事件监听
off(event: 'dismiss', callback: () => void): void取消分享面板关闭事件监听

开发步骤

根据不同的分享场景,参考下表:

分享场景参考链接
分享App Linking直达应用分享App Linking直达应用
分享图片分享图片
分享视频分享视频
分享普通链接直达浏览器分享普通链接直达浏览器
分享文本分享文本

**