HarmonyOS鸿蒙Next中如何调起系统分享弹框(分享文案,文件,图片), 类似安卓系统自带内容分享弹框

HarmonyOS鸿蒙Next中如何调起系统分享弹框(分享文案,文件,图片), 类似安卓系统自带内容分享弹框 如题:如何调起系统分享弹框(分享文案,文件,图片), 类似安卓系统自带内容分享弹框

3 回复

参考demo

import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { BusinessError, request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';
import { fileUri } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  @State imageUri: string = 'https://inews.gtimg.com/om_bt/OM7DU9LBs8fQ2NuR3yTefk9cTN0gGGEoL9dL7AOANr8ecAA/641';
  context = this.context as common.UIAbilityContext;
  filePath = this.context.filesDir + '/test.jpg';

  onPageShow(): void {
    this.checkImageExist()
  }

  checkImageExist(notExistCallback?: Function) {
    fs.access(this.filePath).then((res: boolean) => {
      if (res) {
        console.info("TestShare file exists");
        this.imageUri = fileUri.getUriFromPath(this.filePath);
      } else {
        console.info("TestShare file not exists");
        if (notExistCallback) {
          notExistCallback()
        }
      }
    }).catch((err: BusinessError) => {
      console.info("TestShare access failed with error message: " + err.message + ", error code: " + err.code);
    });
  }

  // 分享图片
  downloadFile(callback: Function) {
    this.checkImageExist(() => {
      request.downloadFile(this.context, {
        url: 'https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2019-11-22%2F5dd7afa7df0fc.jpg&thumburl=https%3A%2F%2Fimg1.baidu.com%2Fit%2Fu%3D2205810988%2C4283060315%26fm%3D253%26fmt%3Dauto%26app%3D138%26f%3DJPEG%3Fw%3D800%26h%3D500',
        filePath: this.filePath,
        background: true
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
          console.info("TestShare download receivedSize:" + receivedSize + " totalSize:" + totalSize);
        });
        downloadTask.on('complete', () => {
          console.info('TestShare download complete');
          let file = fs.openSync(this.filePath, fs.OpenMode.READ_WRITE);
          console.info('TestShare The content of file: %{public}s', 'file:/' + this.filePath);
          let arrayBuffer = new ArrayBuffer(1024);
          let readLen = fs.readSync(file.fd, arrayBuffer);
          let buf: buffer.Buffer = buffer.from(arrayBuffer, 0, readLen);
          console.info('TestShare The content of file: %{public}s', buf.toString());
          fs.closeSync(file);
          callback()
        })
      }).catch((err: BusinessError) => {
        console.error(`TestShare Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    })
  }

  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', () => {
      console.log('TestShare Share panel closed');
      // 分享结束,可处理其他业务。
    });
    // 进行分享面板显示
    controller.show(this.context, {
      previewMode: systemShare.SharePreviewMode.DETAIL,
      selectionMode: systemShare.SelectionMode.SINGLE
    });
  }

  build() {
    Column({space: 10}) {
      Button('查看并下载图片')
        .onClick(() => {
          if (this.imageUri !== '') {
            return;
          }
          this.downloadFile(() => {
            this.imageUri = fileUri.getUriFromPath(this.filePath);
          })
        }
      )
      Image(this.imageUri)
        .width(200)
        .height(200)
        .backgroundColor(Color.Gray)
      Button('系统分享')
        .onClick(() => {
          this.TestSystemShare()
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

更多关于HarmonyOS鸿蒙Next中如何调起系统分享弹框(分享文案,文件,图片), 类似安卓系统自带内容分享弹框的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,调起系统分享弹框可以通过IntentOperation实现。首先,创建一个Intent对象,设置ActionIntent.ACTION_SEND。然后,通过Operation指定要分享的内容类型(如文本、文件或图片),并调用startAbility方法启动分享弹框。

例如,分享文本时,可以设置Intenttype"text/plain",并通过Intent.setParam方法传递文本内容。分享文件或图片时,设置type为对应的MIME类型(如"image/jpeg"),并通过Intent.setParam传递文件或图片的URI。最后,调用startAbility方法,系统会自动调起分享弹框。

具体代码如下:

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

let context = ...; // 获取Ability上下文
let intent = new Intent();
intent.action = Intent.ACTION_SEND;

// 分享文本
intent.type = "text/plain";
intent.setParam(Intent.PARAM_TEXT, "这是要分享的文本");

// 分享文件或图片
// intent.type = "image/jpeg";
// intent.setParam(Intent.PARAM_URI, "file://path/to/image.jpg");

context.startAbility(intent)
    .then(() => {
        console.log("分享弹框已调起");
    })
    .catch((err) => {
        console.error("调起分享弹框失败: " + JSON.stringify(err));
    });

通过这种方式,可以实现在HarmonyOS中调起系统分享弹框,类似于安卓系统的内容分享功能。

在HarmonyOS鸿蒙Next中,可以通过ShareOptionsShareDialog调起系统分享弹框。首先,创建ShareOptions对象,设置分享的文案、文件或图片等数据。然后,使用ShareDialogshow方法显示分享弹框。示例代码如下:

ShareOptions shareOptions = new ShareOptions.Builder()
    .setText("分享文案")
    .setUri(Uri.parse("文件或图片路径"))
    .build();

ShareDialog shareDialog = new ShareDialog(context);
shareDialog.show(shareOptions);

确保在AndroidManifest.xml中声明了必要的权限。

回到顶部