HarmonyOS鸿蒙Next中实现系统分享功能示例代码

HarmonyOS鸿蒙Next中实现系统分享功能示例代码

介绍

本示例基于Share Kit能力实现了宿主应用分享图片的功能。开发者可结合具体业务场景设定目标应用并处理分享内容。

实现系统分享功能源码链接

效果预览

图片名称

使用说明

  1. 点击“查看并下载图片”按钮,从网络上下载图片。
  2. 点击“系统分享”按钮,选择图片,在底部选择shareget可拉起接受方应用,分享图片。

实现思路

分享图片

使用request.downloadFile接口,根据开发者自己设定的图片网址下载图片。构造分享数据,首先配置一条有效数据信息,获取待分享图片的沙箱路径,使用fileUri.getUriFromPath接口将沙箱路径转为文件URI,最后启动分享面板分享图片。核心代码如下,源码参考

Index.ets

TestSystemShare() {
    // 构造ShareData,需配置一条有效数据信息
    let data: systemShare.SharedData = new systemShare.SharedData({
      utd: utd.UniformDataType.PLAIN_TEXT,
      content: 'Hello HarmonyOS'
    });
    // 获取文件的沙箱路径
    let pathInSandbox = this.context.filesDir + '/test.jpg';
    // 将沙箱路径转换为uri
    let uri = fileUri.getUriFromPath(pathInSandbox);
    // 添加多条记录
    data.addRecord({
      utd: utd.UniformDataType.PNG,
      uri: uri
    });
    // 构建ShareController
    let controller: systemShare.ShareController = new systemShare.ShareController(data);
    // 注册分享面板关闭监听
    controller.on('dismiss', () => {
      hilog.info(0x0001,"JSAPP",'TestShare Share panel closed');
      // 分享结束,可处理其他业务。
    });
    // 进行分享面板显示
    controller.show(this.context, {
      previewMode: systemShare.SharePreviewMode.DETAIL,
      selectionMode: systemShare.SelectionMode.SINGLE
    });
  }

更多关于HarmonyOS鸿蒙Next中实现系统分享功能示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中实现系统分享功能,可以使用@ohos.app.ability.common模块中的Share类。以下是一个简单的示例代码:

import common from '@ohos.app.ability.common';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

// 创建Share实例
let share = new common.Share();

// 设置分享内容
let shareText = '这是一段分享的文本内容';
let shareOptions = {
  title: '分享标题',
  text: shareText,
  type: 'text/plain'
};

// 调用系统分享
share.share(shareOptions).then(() => {
  console.log('分享成功');
}).catch((err) => {
  console.error('分享失败', err);
});

这段代码首先导入了Share类和dataSharePredicates模块,然后创建了一个Share实例。接着,设置了分享的内容和选项,最后调用share方法进行系统分享。分享成功或失败时,分别输出相应的日志信息。

更多关于HarmonyOS鸿蒙Next中实现系统分享功能示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,系统分享功能可以通过IntentShareDialog来实现。以下是一个简单的示例代码:

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ShareDialog;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        Text text = (Text) findComponentById(ResourceTable.Id_text);
        text.setClickedListener(component -> showShareDialog());
    }

    private void showShareDialog() {
        ShareDialog shareDialog = new ShareDialog(this);
        shareDialog.setTitle("分享");
        shareDialog.setContent("分享内容");
        shareDialog.show();
    }
}

在这个示例中,创建了一个ShareDialog,用户点击文本组件时会弹出分享对话框。setContent方法用于设置分享的内容。

回到顶部