如何将图片文本视频分享给其他应用

​针对图片文本视频分享给其他应用的demo

HarmonyOS
2024-05-21 20:32:00
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
vclearner

生成BuildProfile类文件后,在代码中可以通过相对路径引入该文件,如在HAR模块的Index.ets文件中使用该文件。

参考代码:

// api ->systemShare -> index.d.ts 
/* 
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. 
*/ 
import type Want from '@ohos.app.ability.Want'; 
import type common from '@ohos.app.ability.common'; 
  
declare namespace systemShare { 
export class SharedData { 
constructor(record: SharedRecord); 
  
addRecord(record: SharedRecord): void; 
  
getRecords(): Array<SharedRecord>; 
} 
  
export interface SharedRecord { 
utd: string; 
content?: string; 
uri?: string; 
title?: string; 
label?: string; 
description?: string; 
thumbnail?: Uint8Array; 
extraData?: Record<string, string>; 
} 
  
export interface Offset { 
x: number; 
y: number; 
} 
  
export interface Size { 
width: number; 
height: number; 
} 
  
export interface ShareControllerAnchor { 
windowOffset: Offset; 
size?: Size; 
} 
  
export enum SharePreviewMode { 
DEFAULT = 0, 
DETAIL 
} 
  
export enum SelectionMode { 
SINGLE = 0, 
BATCH = 1, 
ALBUM = 3 
} 
  
export interface AlbumInfo { 
uri: string; 
order: 'asc' | 'desc'; 
orderBy: string; 
} 
  
export interface ShareControllerOptions { 
selectionMode?: SelectionMode; 
anchor?: ShareControllerAnchor | string; 
previewMode?: SharePreviewMode; 
albumInfo?: AlbumInfo; 
} 
  
export class ShareController { 
constructor(data: SharedData); 
  
show(context: common.UIAbilityContext, options: ShareControllerOptions): Promise<void>; 
  
on(event: 'dismiss', callback: () => void): void; 
  
off(event: 'dismiss', callback: () => void): void; 
} 
  
export interface ContactInfo { 
contactType: string; 
contactId: string; 
} 
  
export function getSharedData(want: Want): Promise<SharedData>; 
  
export function getWant(data: SharedData): Promise<Want>; 
} 
  
export default systemShare; 
 
// api ->systemShare -> index.js 
/* 
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. 
*/ 
  
// @ts-ignore 
import systemShare from '@hms.collaboration.systemShare'; 
  
export default systemShare;
// entryability-> EntryAbility.ets 
import hilog from '@ohos.hilog'; 
import UIAbility from '@ohos.app.ability.UIAbility'; 
import window from '@ohos.window'; 
import Logger from '../utils/Logger'; 
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; 
import { BusinessError } from '@ohos.base'; 
  
const logger = Logger.getLogger('EntryAbility'); 
  
const REQUIRED_PERMISSIONS: Permissions[] = [ 
'ohos.permission.READ_MEDIA', 
'ohos.permission.WRITE_MEDIA', 
'ohos.permission.READ_DOCUMENT', 
'ohos.permission.WRITE_DOCUMENT', 
'ohos.permission.READ_IMAGEVIDEO', 
'ohos.permission.WRITE_IMAGEVIDEO' 
]; 
  
  
export default class EntryAbility extends UIAbility { 
onWindowStageCreate(windowStage: window.WindowStage): void { 
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
try { 
atManager.requestPermissionsFromUser(this.context, REQUIRED_PERMISSIONS).then((data) => { 
let results: Array<number> = data.authResults; 
for (let i = 0; i < results.length; i++) { 
if (results[i]) { 
logger.error('error', data.permissions[i]); 
this.context.terminateSelf(); 
return; 
} 
} 
let storage: LocalStorage = new LocalStorage(); 
storage.setOrCreate('context', this.context); 
windowStage.loadContent('pages/Index', storage); 
}, (err: BusinessError) => { 
logger.error('error' + JSON.stringify(err)); 
}) 
} catch (err) { 
logger.error('error' + JSON.stringify(err)); 
} 
} 
}
// mock -> index.ets 
/* 
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. 
*/ 
import systemShare from '../api/systemShare'; 
import fs from '@ohos.file.fs'; 
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; 
import fileUri from '@ohos.file.fileuri'; 
  
const STORAGE_DOC_ROOT = 'file://docs/storage/Users/currentUser/Documents/'; 
  
export type MockRecordType = 'image' | 'video' | 'text' | 'folder' | 'ppt' | 'doc'; 
  
const fileMap: Record<string, string> = { 
'image': 'image.png', 
'video': 'video.mp4', 
'text': 'text.txt', 
'ppt': 'powerpoint.mp4', 
'doc': 'document.txt', 
'folder': 'folder' 
} 
  
const utdMap: Record<string, string> = { 
'image': uniformTypeDescriptor.UniformDataType.IMAGE, 
'video': uniformTypeDescriptor.UniformDataType.VIDEO, 
'text': uniformTypeDescriptor.UniformDataType.FILE, 
'ppt': 'com.microsoft.powerpoint.ppt', 
'doc': 'com.microsoft.word.doc', 
'folder': uniformTypeDescriptor.UniformDataType.FOLDER 
} 
  
function createRecord(utd: string): systemShare.SharedRecord { 
return { 
utd: utd 
}; 
} 
  
class SystemShareMockKit { 
userFile(fileType: MockRecordType): systemShare.SharedRecord { 
if (!fileMap[fileType]) { 
throw new Error('Not exist'); 
} 
let record = createRecord(utdMap[fileType]); 
record.uri = STORAGE_DOC_ROOT + fileMap[fileType]; 
return record; 
} 
  
async sandBoxFile(fileType: MockRecordType): Promise<systemShare.SharedRecord> { 
if (!fileMap[fileType]) { 
throw new Error('Not exist'); 
} 
let record = createRecord(utdMap[fileType]); 
let path = getContext().filesDir + '/' + fileMap[fileType]; 
record.uri = fileUri.getUriFromPath(path); 
if (fs.accessSync(path)) { 
return record; 
} 
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 
let array = await getContext().resourceManager.getRawFileContent(fileMap[fileType]); 
fs.writeSync(file.fd, array.buffer); 
fs.closeSync(file.fd); 
return record; 
}
// pages->index.ets 
/* 
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. 
*/ 
import systemShare from '../api/systemShare'; 
import promptAction from '@ohos.promptAction'; 
import Logger from '../utils/Logger'; 
import { systemShareMockKit as shareMock, systemShareMockKit } from '../mock'; 
import common from '@ohos.app.ability.common'; 
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; 
import mediaquery from '@ohos.mediaquery'; 
import componentUtils from '@ohos.arkui.componentUtils'; 
//import ufm from '@ohos.filemanagement.userFileManager'; 
import dataSharePredicates from '@ohos.data.dataSharePredicates'; 
  
const storage = LocalStorage.getShared(); 
const logger = Logger.getLogger('Index'); 
  
@Entry(storage) 
@Component 
struct UIExtPreviewDemo { 
@LocalStorageLink('context') context: common.UIAbilityContext = storage.get<common.UIAbilityContext>('context')!; 
@State selectionMode: systemShare.SelectionMode = systemShare.SelectionMode.SINGLE; 
@State previewMode: systemShare.SharePreviewMode = systemShare.SharePreviewMode.DEFAULT; 
anchor?: systemShare.ShareControllerAnchor; 
@State anchorType: 'id' | 'rect' = 'rect'; 
@State usePrototype: boolean = false; 
private xsListener = mediaquery.matchMediaSync(`screen and (width <= ${vp2px(320)})`); 
private smListener = mediaquery.matchMediaSync(`screen and (width > ${vp2px(320)}) and (width <= ${vp2px(600)})`); 
private mdListener = mediaquery.matchMediaSync(`screen and (width > ${vp2px(600)}) and (width <= ${vp2px(840)})`); 
private lgListener = mediaquery.matchMediaSync(`screen and (width > ${vp2px(840)})`); 
  
aboutToAppear() { 
logger.info('xs', this.xsListener.matches, this.xsListener.media); 
logger.info('sm', this.smListener.matches, this.smListener.media); 
logger.info('md', this.mdListener.matches, this.mdListener.media); 
logger.info('lg', this.lgListener.matches, this.lgListener.media); 
this.xsListener.on('change', result => logger.info('xs, change', result.matches)); 
this.smListener.on('change', result => logger.info('sm, change', result.matches)); 
this.mdListener.on('change', result => logger.info('md, change', result.matches)); 
this.lgListener.on('change', result => logger.info('lg, change', result.matches)); 
} 
  
@Builder 
PreviewModeOption(name: string, mode: systemShare.SharePreviewMode) { 
Row({ space: 5 }) { 
Radio({ value: name, group: 'previewMode' }) 
.onChange((checked: boolean) => { 
if (checked) { 
this.previewMode = mode; 
} 
}) 
.checked(this.previewMode === mode) 
Text(name) 
} 
} 
  
@Builder 
SelectionModeOption(name: string, mode: systemShare.SelectionMode) { 
Row({ space: 5 }) { 
Radio({ value: name, group: 'SelectionMode' }) 
.onChange((checked: boolean) => { 
if (checked) { 
this.selectionMode = mode; 
} 
}) 
.checked(this.selectionMode === mode) 
Text(name) 
} 
} 
  
@Builder 
AnchorOptions(name: string, type: 'id' | 'rect') { 
Row({ space: 5 }) { 
Radio({ value: name, group: 'Anchor' }) 
.onChange((checked: boolean) => { 
if (checked) { 
this.anchorType = type; 
} 
}) 
.checked(this.anchorType === type) 
Text(name) 
} 
.height(80) 
} 
  
build() { 
Scroll() { 
  
Column({ space: 10 }) { 
Text('分享预览模式') 
Row({ space: 10 }) { 
this.PreviewModeOption('卡片', systemShare.SharePreviewMode.DEFAULT) 
  
this.PreviewModeOption('展开', systemShare.SharePreviewMode.DETAIL) 
} 
Text('分享选择模式') 
Row({ space: 10 }) { 
this.SelectionModeOption('单选', systemShare.SelectionMode.SINGLE) 
  
this.SelectionModeOption('批量', systemShare.SelectionMode.BATCH) 
  
this.SelectionModeOption('相册', systemShare.SelectionMode.ALBUM) 
} 
  
  
Row({ space: 10 }) { 
this.AnchorOptions('视图ID', 'id') 
  
this.AnchorOptions('视图矩形', 'rect') 
} 
  
Stack({ alignContent: Alignment.Center }) { 
Button('test', { type: ButtonType.Normal }).width('100%').height('100%') 
.onMouse(async (event: MouseEvent) => { 
if (event.button === MouseButton.Right && event.action === MouseAction.Release) { 
logger.info('on mouse right', event.windowY, event.windowY); 
let data = systemShareMockKit.createSharedData(await systemShareMockKit.sandBoxFile('image')); 
let controller = new systemShare.ShareController(data); 
controller 
.show(this.context, { 
selectionMode: this.selectionMode, 
previewMode: this.previewMode, 
anchor: { 
windowOffset: { x: vp2px(event.windowX), y: vp2px(event.windowY) }, 
size: { width: 5, height: 5 } 
} 
}); 
} 
}) 
Rect({ width: 100, height: 15 }) 
.id('anchor') 
.fill(Color.Red) 
} 
.height(500) 
.width('100%') 
  
Row({ space: 10 }) { 
Checkbox({ name: 'prototype' }).onChange(value => { 
this.usePrototype = value; 
}) 
  
Text('拉起原型窗') 
} 
  
Text('HarmonyOS 分享 Demo').fontSize(24) 
Button('转') 
.onClick(() => { 
  
}) 
  
if (this.selectionMode === systemShare.SelectionMode.BATCH) { 
Button('批量 - 500') 
.onClick(async () => { 
let data = shareMock.createSharedData(await shareMock.sandBoxFile('image')); 
for (let i = 0; i < 300; i++) { 
data.addRecord(await shareMock.sandBoxFile('image')); 
} 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多文件(包含文件夹、图片、视频、普通文件)') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('folder'), shareMock.userFile('image'), 
shareMock.userFile('video'), shareMock.userFile('text')); 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多文件(不包含文件夹,包含图片、视频、普通文件)') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('image'), 
shareMock.userFile('video'), shareMock.userFile('text')); 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多文件(不包含文件夹和图片和视频,仅包含普通文件)') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('text'), shareMock.userFile('text')); 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多文件 - 测试') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('text'), 
shareMock.userFile('ppt'), 
shareMock.userFile('folder'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('image'), 
shareMock.userFile('video'), 
shareMock.userFile('doc')); 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多个图片') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('image'), shareMock.userFile('image'), 
shareMock.userFile('image')); 
this.showSharePanel(data); 
}) 
  
Button('批量 - 多个视频') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('video'), shareMock.userFile('video'), 
shareMock.userFile('video')); 
this.showSharePanel(data); 
}) 
} 
  
if (this.selectionMode === systemShare.SelectionMode.SINGLE) { 
Button('单选 - 沙箱文件') 
.onClick(async () => { 
let data = shareMock.createSharedData(await shareMock.sandBoxFile('text')); 
this.showSharePanel(data); 
}) 
Button('单选 - 用户文件') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('text')); 
this.showSharePanel(data); 
}) 
Button('单选 - 用户图片') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('image')); 
this.showSharePanel(data); 
}) 
  
Button('单选 - 用户文件夹') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('folder')); 
this.showSharePanel(data); 
}) 
Button('单选 - 用户视频') 
.onClick(() => { 
let data = shareMock.createSharedData(shareMock.userFile('video')); 
this.showSharePanel(data); 
}) 
Button('单选 - 沙箱图片') 
.onClick(async () => { 
let data = shareMock.createSharedData(await shareMock.sandBoxFile('image')); 
this.showSharePanel(data); 
}) 
  
Button('单选 - 链接/图片') 
.onClick(() => { 
logger.info('ready'); 
let data = shareMock.createSharedData({ 
utd: uniformTypeDescriptor.UniformDataType.IMAGE, 
title: 'HarmonyOS', 
uri: 'file://docs/storage/Users/currentUser/Documents/image.png', 
label: '网页海报' 
}, { 
utd: uniformTypeDescriptor.UniformDataType.HYPERLINK, 
content: 'www.harmonyos.com', 
description: '123134214', 
title: 'HarmonyOS' 
}); 
this.showSharePanel(data); 
}) 
Button('单选 - 链接/图片/文本') 
.onClick(() => { 
let data = shareMock.createSharedData({ 
utd: uniformTypeDescriptor.UniformDataType.IMAGE, 
title: 'HarmonyOS', 
uri: 'file://docs/storage/Users/currentUser/Documents/image.png', 
label: '网页海报' 
}, { 
utd: uniformTypeDescriptor.UniformDataType.HYPERLINK, 
content: 'www.harmonyos.com', 
title: 'HarmonyOS' 
}, { 
utd: uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, 
title: 'HarmonyOS WebPage', 
content: 'www.harmonyos.com, HarmonyOS' 
}); 
  
this.showSharePanel(data); 
}) 
Button('单选 - 文本') 
.onClick(() => { 
let data = shareMock.createSharedData({ 
utd: uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, 
content: 'www.harmonyos.com', 
title: 'HarmonyOS', 
description: 'Hello HarmonyOS' 
}); 
  
this.showSharePanel(data); 
}) 
} 
if (this.selectionMode === systemShare.SelectionMode.ALBUM) { 
// Button('相册 - 收藏') 
// .onClick(async () => { 
// let mgr = ufm.getUserFileMgr(getContext()); 
// let result = await mgr.getAlbums(ufm.AlbumType.SYSTEM, ufm.AlbumSubType.FAVORITE); 
// let album = await result.getFirstObject(); 
// let assets = await album.getPhotoAssets({ 
// fetchColumns: [], 
// predicates: new dataSharePredicates.DataSharePredicates() 
// }); 
// if (assets.getCount() === 0) { 
// promptAction.showToast({ 
// message: '请收藏至少一张图片' 
// }); 
// return; 
// } 
// let data = shareMock.createSharedData(this.getPhotoRecord(await assets.getPositionObject(0))); 
// this.showSharePanel(data, { 
// uri: album.albumUri, 
// order: 'asc', 
// orderBy: ufm.AlbumKey.DATE_ADDED.toString() 
// }); 
// }) 
} 
} 
.alignItems(HorizontalAlign.Center) 
} 
.width('100%') 
.height('100%') 
} 
  
// private getPhotoRecord(asset: ufm.FileAsset): systemShare.SharedRecord { 
// return { 
// uri: asset.uri, 
// utd: asset.fileType === ufm.FileType.IMAGE 
// ? uniformTypeDescriptor.UniformDataType.IMAGE 
// : uniformTypeDescriptor.UniformDataType.VIDEO 
// }; 
// } 
  
private showSharePanel(data: systemShare.SharedData, albumInfo?: systemShare.AlbumInfo): void { 
let controller = new systemShare.ShareController(data); 
controller.on('dismiss', () => { 
promptAction.showToast({ 
message: 'Share panel disappeared' 
}); 
}); 
logger.info('show start'); 
if (this.usePrototype) { 
controller 
.show(this.context, { 
selectionMode: this.selectionMode, 
previewMode: this.previewMode, 
albumInfo: albumInfo, 
anchor: this.anchorType === 'id' ? 'anchor' : componentUtils.getRectangleById('anchor') 
}); 
} 
logger.info('show end'); 
} 
} 
// utils-> Logger.ts 
/* 
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. 
*/ 
  
import hilog from '@ohos.hilog'; 
  
const TAG = 'SystemShareDemo'; 
const SYSTEM_SHARE_DOMAIN = 0x6DFE; 
  
const loggerMap: Map<string, Logger> = new Map(); 
  
class Logger { 
private static readonly singleton = new Logger(); 
  
private constructor(tag?: string) { 
this._tag = tag; 
} 
  
private _tag: string | undefined = undefined; 
  
private get tag(): string { 
return this._tag ? `[${this._tag}]` : ''; 
} 
  
static getLogger(tag?: string): Logger { 
return tag ? Logger.getOrCreate(tag) : Logger.singleton; 
} 
  
private static getOrCreate(tag: string): Logger { 
let instance = loggerMap.get(tag); 
if (!instance) { 
instance = new Logger(tag); 
loggerMap.set(tag, instance); 
} 
return instance; 
} 
  
// eslint-disable-next-line @typescript-eslint/no-explicit-any 
info(...args: any[]): void { 
hilog.info(SYSTEM_SHARE_DOMAIN, `${TAG}`, `${this.tag} ${args.join(' ')}`); 
} 
  
// eslint-disable-next-line @typescript-eslint/no-explicit-any 
debug(...args: any[]): void { 
hilog.debug(SYSTEM_SHARE_DOMAIN, `${TAG}`, `${this.tag} ${args.join(' ')}`); 
} 
  
// eslint-disable-next-line @typescript-eslint/no-explicit-any 
warn(...args: any[]): void { 
hilog.warn(SYSTEM_SHARE_DOMAIN, `${TAG}`, `${this.tag} ${args.join(' ')}`); 
} 
  
// eslint-disable-next-line @typescript-eslint/no-explicit-any 
error(...args: any[]): void { 
hilog.error(SYSTEM_SHARE_DOMAIN, `${TAG}`, `${this.tag} ${args.join(' ')}`); 
} 
} 
  
export default Logger; 
// 模块级别 module.json5 
{ 
"module": { 
"name": "entry", 
"type": "entry", 
"description": "$string:module_desc", 
"mainElement": "EntryAbility", 
"deviceTypes": [ 
"phone", 
"tablet", 
"2in1" 
], 
"deliveryWithInstall": true, 
"installationFree": false, 
"pages": "$profile:main_pages", 
"abilities": [ 
{ 
"name": "EntryAbility", 
"srcEntry": "./ets/entryability/EntryAbility.ets", 
"description": "$string:EntryAbility_desc", 
"icon": "$media:icon", 
"label": "$string:EntryAbility_label", 
"startWindowIcon": "$media:startIcon", 
"startWindowBackground": "$color:start_window_background", 
"orientation": "auto_rotation", 
"exported": true, 
"skills": [ 
{ 
"entities": [ 
"entity.system.home" 
], 
"actions": [ 
"action.system.home" 
] 
} 
] 
} 
], 
"requestPermissions": [ 
// { 
// "name": "ohos.permission.FILE_ACCESS_MANAGER" 
// }, 
{ 
"name": "ohos.permission.WRITE_MEDIA" 
}, 
{ 
"name": "ohos.permission.READ_MEDIA" 
}, 
{ 
"name": "ohos.permission.READ_IMAGEVIDEO" 
}, 
{ 
"name": "ohos.permission.WRITE_IMAGEVIDEO" 
}, 
{ 
"name": "ohos.permission.READ_DOCUMENT" 
}, 
{ 
"name": "ohos.permission.WRITE_DOCUMENT" 
} 
] 
} 
}
分享
微博
QQ
微信
回复
2024-05-22 16:12:43
相关问题
鸿蒙如何将音频文件转成文本
3309浏览 • 1回复 待解决
如何将图片PixelMap压缩到指定大小
566浏览 • 1回复 待解决
ets中如何将图片转为byte[]?
1851浏览 • 1回复 待解决
如何将三方应用改为系统应用
488浏览 • 2回复 已解决
如何将视频保存到相册以及主机端
4184浏览 • 1回复 待解决
如何将像素点保存到图片文件
1114浏览 • 1回复 待解决
有谁知道如何将图片保存到相册
452浏览 • 1回复 待解决
如何将一张图片转化为PixelMapElement
8474浏览 • 1回复 待解决
如何将ArrayBuffer转成string
700浏览 • 1回复 待解决
如何将PixelMap压缩到指定大小
502浏览 • 1回复 待解决
如何将Map/HashMap转为Object对象?
567浏览 • 1回复 待解决
如何按钮添加图片
1997浏览 • 3回复 待解决
鸿蒙-富文本如何添加图片
5493浏览 • 1回复 待解决
分享沙箱文件,应用分享单个文件
490浏览 • 1回复 待解决
如何把公共事件发布其他设备
3184浏览 • 1回复 待解决
如何将背景颜色设置为透明
1095浏览 • 1回复 待解决
如何将 Checkbox 的文字放在左边 ?
9533浏览 • 1回复 待解决
求大佬告知如何将http文件上传
523浏览 • 1回复 待解决