This module provides the functions of creating shared data and starting the sharing panel, and offers multiple standard sharing services, such as sharing data to other apps, copying data, and printing files.
-
If your app functions as a host app that shares content to other apps, you need to integrate Share Kit into your app so that it can configure, start, and close the sharing panel.
-
The sharing panel configuration includes the data object, view presentation mode, and preview mode.
Model restriction: APIs of this module can be used only in the stage model.
Since: 4.1.0(11)
Modules to Import
import { systemShare } from '@kit.ShareKit'; SharedRecord
Constructs a shared data record, including the data type, data content, and description.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
| utd | string | No | No | Uniform data type. For details, please refer to @ohos.data.uniformTypeDescriptor (Uniform Data Definition and Description). You are advised to pass a precise data type to match the most suitable target app. For details, please refer to Share Kit Experience Specifications. |
| title | string | No | Yes | Title of the shared content. You are advised to set this parameter if the content is a text or link. When this parameter is empty, if the shared content is a piece of text, the text content is used as the value of title; if the shared content is a file, the file name is used as the value of title. |
| label | string | No | Yes | Label indicating the current data record type. This parameter is valid in the single selection mode. The default value is the label corresponding to UniformDataType. The options are: HYPERLINK: link; HTML: webpage; TEXT: text; VIDEO: video; AUDIO: music; IMAGE: image; FILE: file. |
| description | string | No | Yes | Data record description. The default value is an empty string. |
| thumbnail | Uint8Array | No | Yes | Data record thumbnail. When this parameter is empty, the default icon matching the shared content type is used as the thumbnail. You are advised to pass a thumbnail matching the data record. If no matching thumbnail is available, you can pass the app icon. Note: The image size must be less than 32 KB. If the image is too large, the want data may exceed the limit and sharing may fail to be started. In this case, you can use ImagePacker.packToData to compress the image. |
| thumbnailUri | string | No | Yes | Data record thumbnail URI. When this parameter is empty, the default icon matching the shared content type is used as the thumbnail. The following URI types are supported: App file URI. For details, please refer to Sharing an Application File. User file URI. For details, please refer to User File URI. Since: 5.0.0(12) Note: If both this parameter and the thumbnail parameter exist, the thumbnail parameter is used preferentially. |
| uri | string | No | Yes | Data record URI. The following URI types are supported: App file URI. For details, please refer to Sharing an Application File. User file URI. For details, please refer to User File URI. Note: You can use the fileUri.getUriFromPath method to obtain the file URI from the sandbox path. At least one of content and uri must be set. Otherwise, the sharing will fail. |
| content | string | No | Yes | Data record content. Content of the link (including links of App Linking) and text types is passed through this parameter. Note: At least one of content and uri must be set. Otherwise, the sharing will fail. |
| extraData | Record<string, string | number | boolean | Array<string | number | boolean>> | No | Yes | Extension data, used to share custom extension content with the target app or device. |
| revisitShareRecordData | RevisitShareRecordData | No | Yes | Used to generate a QR code for revisiting the shared content. For details about the supported types, please refer to RevisitShareRecordType. Since: 6.1.0(23) |
ShareControllerOptions
Sharing controller configuration items, such as the preview mode of the shared content, selection mode, and other information, which determine the display style of the sharing panel.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Required permission: To use the appLaunchTrustInfo field, you need to apply for the ohos.permission.SET_SYSTEMSHARE_APPLAUNCHTRUSTLIST permission. This restricted permission is available only to enterprise apps, enabling them to restrict target apps to a set of trusted apps for secure internal data sharing. For details about how to apply for a restricted permission, please refer to Requesting Restricted Permissions.
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
| anchor | ShareControllerAnchor | string | No | Yes | When the value type is string, this parameter indicates the ID of the component associated with the sharing panel. For details, please refer to Common Attributes. When the value type is ShareControllerAnchor, this parameter indicates the anchor position. If this parameter is not passed, the sharing panel will be displayed in the default position (center). |
| previewMode | SharePreviewMode | No | Yes | Preview mode. The default mode is card. |
| selectionMode | SelectionMode | No | Yes | Selection mode. The default mode is single selection. |
| excludedAbilities | Array<ShareAbilityType> | No | Yes | List of capabilities that do not need to be displayed in the operation area. Since: 5.0.0(12) |
| appLaunchTrustInfo | Array<string> | No | Yes | List of target apps that can be shared, which can be specified by configuring the list of unique app identifiers (appIdentifier field). The system reads only the first 50 configuration items, and the excess configuration items do not take effect. To use this function, you need to apply for the ohos.permission.SET_SYSTEMSHARE_APPLAUNCHTRUSTLIST permission. This capability is restricted and can only be used by enterprise apps to restrict internal data sharing to the list of apps trusted by the group. Since: 6.0.1(21) |
ShareControllerAnchor
Anchor of the sharing pop-up window. The sharing panel will adapt to the screen size and may appear as a pop-up window depending on the screen size.
If the device screen width is small, the sharing panel will not be displayed in pop-up mode, but displayed in modal mode instead.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
| windowOffset | Offset | No | No | Window offset of the sharing controller. You are advised to set the coordinates of the vertex in the upper left corner of the component. |
| size | Size | No | Yes | Dimensions of the anchor rectangle. The anchor is a point by default, that is, the width and height are both 0. |
Offset
Window offset to the anchor.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
| x | number | No | No | X coordinate, in pixels. |
| y | number | No | No | Y coordinate, in pixels. |
Size
Dimensions of the anchor rectangle. The anchor is a point by default, that is, the width and height are both 0.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
| width | number | No | No | Component width, in pixels. Negative values are treated as 0. |
| height | number | No | No | Component height, in pixels. Negative values are treated as 0. |
ShareOperationResult
Return value of the shareCompleted event, which is used to obtain information about the sharing channel.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.1.0(18)
| Name | Type | Read-Only | Optional | Description |
| targetAbilityInfo | ShareAbilityInfo | No | No | Information about the sharing channel. |
ShareAbilityInfo
Information about the sharing channel.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.1.0(18)
| Name | Type | Read-Only | Optional | Description |
| name | string | No | No | Name of the sharing channel. A system operation name, which has a fixed value. For details, please refer to the enumerated values of ShareAbilityName. A non-system operation name, which is in [bundleName]#[moduleName]#[abilityName] format. |
RevisitShareRecordData
Revisits the shared data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 6.1.0(23)
Parameters:
| Name | Type | Read-Only | Optional | Description |
| revisitShareRecordType | RevisitShareRecordType | No | No | Type of the revisited shared data. |
| generatedImageUri | string | No | No | URI of the generated shared image (app file URI), which is used to write the drawing result or preview the image. You need to create an empty image file in this path. The supported image file types include PNG and JPG. App file URI. For details, please refer to Sharing an Application File. Note: You can use the fileUri.getUriFromPath method to obtain the file URI from the sandbox path. |
ReadingExtendedShareRecordData
Extended data records for the reading sharing scenario. ReadingExtendedShareRecordData is inherited from RevisitShareRecordData.
This API takes effect when utd is set to utd.UniformDataType.TEXT and revisitShareRecordType is set to RevisitShareRecordType.READING_SHARE.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 6.1.0(23)
Parameters:
| Name | Type | Read-Only | Optional | Description |
| sourceTitle | string | No | No | Source title (original article/book name), which is used to generate the title on the shared image. Length limit: When readingShareStyle is set to STYLE_HIGHLIGHT_CONTENT, a maximum of two lines can be displayed. The default font size is 16 vp. If the text exceeds the limit, the extra part is displayed as an ellipsis (...). When readingShareStyle is set to STYLE_HIGHLIGHT_TITLE, a maximum of two lines can be displayed. The default font size is 24 vp. If the space is insufficient, the font size is reduced to 18 vp level by level. If the text still cannot be completely displayed at the font size of 18 vp, the extra part at the end is displayed as an ellipsis (...). |
| appLink | string | No | No | App link of the article (HTTPS link format). This parameter is mandatory when ReadingExtendedData is not empty. Length limit: The total length of the concatenated value of appLink and appLinkExtraInfo cannot exceed 512 characters. |
| readingShareStyle | ReadingShareRecordStyle | No | Yes | Data type of the reading sharing template. The default value is STYLE_HIGHLIGHT_CONTENT. |
| subtitle | string | No | Yes | Subtitle (such as the chapter or paragraph information). This parameter takes effect when readingShareStyle is set to STYLE_HIGHLIGHT_TITLE. Length limit: The text is displayed in a single line, and the extra part is displayed as an ellipsis (...). |
| appLinkExtraInfo | string | No | Yes | Supplementary information of the app link, which is concatenated to the app link for QR code generation. For web text selection sharing, it is recommended that the textFragment information (#:~:text=[prefix-,]textStart[,textEnd][,-suffix]) be included for text highlighting. In other scenarios, custom parameters can be included to handle internal logic for accessing a specified in-app page. |
| coverImageUri | string | No | Yes | Cover image URI (app file URI), for example, the path of the book cover image. This parameter takes effect when readingShareStyle is set to STYLE_HIGHLIGHT_TITLE. App file URI. For details, please refer to Sharing an Application File. |
| prefixText | string | No | Yes | Prefix of the selected text. Length limit: A maximum of one line can be displayed. If the text exceeds one line, the prefix part is omitted. |
| suffixText | string | No | Yes | Suffix of the selected text. Length limit: A maximum of two lines can be displayed. If the text exceeds two lines, the suffix part is omitted. |
| author | string | No | Yes | Article author name, which is used to generate the information displayed on the shared image. Length limit: A maximum of one line can be displayed. If the text exceeds one line, the extra part is displayed as an ellipsis (...). |
| publishDate | Date | No | Yes | Article publication date. This parameter takes effect when readingShareStyle is set to STYLE_HIGHLIGHT_CONTENT. |
| sharerName | string | No | Yes | Sharer name. Length limit: A maximum of one line can be displayed. If the text exceeds one line, the extra part is displayed as an ellipsis (...). |
| appSlogan | string | No | Yes | App slogan. Length limit: A maximum of one line can be displayed. The extra part is displayed as an ellipsis (...). |
SharePreviewMode
Preview mode of the shared content. The detailed preview image mode is recommended for images and videos.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Value | Description |
| DEFAULT | 0 | Default mode (thumbnail card). This mode is recommended for text and links. |
| DETAIL | 1 | Detailed preview image. This mode is recommended for images and videos. |
SelectionMode
Selection mode.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
| Name | Value | Description |
| SINGLE | 0 | Single selection mode. When multiple shared data records (SharedRecord) are passed, the user needs to select one from them for sharing. |
| BATCH | 1 | Batch mode, in which all data records are shared. |
ShareAbilityType
Defines system capabilities that are excluded from the operation area.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.0.0(12)
| Name | Value | Description |
| COPY_TO_PASTEBOARD | 0 | Copy. |
| SAVE_TO_MEDIA_ASSET | 1 | Save to Gallery. |
| SAVE_AS_FILE | 2 | Save as. |
| PRINT | 3 | Print. |
| SAVE_TO_SUPERHUB | 4 | Add to SuperHub. |
ShareAbilityResultCode
Result code returned from UIExtensionAbility, which controls the behavior of the sharing panel.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.0.0(12)
| Name | Value | Description |
| ERROR | -1 | An error occurred. If the message parameter is also passed, a toast message will be displayed. |
| BACK | 0 | A user taps the back button. Return to the sharing panel. |
| CLOSE | 1 | A user taps the close button. Close the sharing panel. |
ShareAbilityName
System operation name, which is used to return the sharing result data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.1.0(18)
| Name | Value | Description |
| COPY_TO_PASTEBOARD | 'SystemShare_CopyToPasteboard' | Copy. |
| SAVE_TO_MEDIA_ASSET | 'SystemShare_SaveToMediaAsset' | Save to Gallery. |
| SAVE_AS_FILE | 'SystemShare_SaveAsFile' | Save as. |
| PRINT | 'SystemShare_Print' | Print. |
| SAVE_TO_SUPERHUB | 'SystemShare_Superhub' | Add to SuperHub. |
| COLLECTION | 'SystemShare_Collection' | Celia Knowledge Base. |
| HARMONYSHARE | 'SystemShare_HarmonyShare' | Huawei Share. |
| ENCRYPT | 'SystemShare_Encrypt' | Encrypted share. |
RevisitShareRecordType
Defines the type of the revisited shared data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 6.1.0(23)
| Name | Value | Description |
| READING_SHARE | 1 | Type of the reading shared data. |
ReadingShareRecordStyle
Display template type in the reading sharing scenario.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 6.1.0(23)
| Name | Value | Description |
| STYLE_HIGHLIGHT_CONTENT | 0 | Highlight the selected text. This is the default value. |
| STYLE_HIGHLIGHT_TITLE | 1 | Highlight the title. |
SharedData
Shared data object, which provides the method of encapsulating a group of data records.
A shared data object must have at least one record. The first record must be passed using the first parameter of the constructor during SharedData instantiation. If the shared data contains multiple records, you need to use the addRecord(record: SharedRecord) method to add subsequent records.
A maximum of 500 data records are supported, and the total data size cannot exceed 200 KB, which is the upper limit for transmission using IPC.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
[h2]constructor
constructor(record: SharedRecord)
Constructs a SharedData object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| record | SharedRecord | Yes | Shared data record. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
let data: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.PLAIN_TEXT,
content: 'Hello HarmonyOS'
}); [h2]addRecord
addRecord(record: SharedRecord): void
Adds a data record to the current shared data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| record | SharedRecord | Yes | SharedRecord object, which is to be added to SharedData. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and Share Kit Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
| 1003700001 | The number of records exceeds the maximum. |
Example:
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.IMAGE,
// ...
title: 'Picture Title',
description: 'Picture Description',
label: 'Poster'
});
try {
shareData.addRecord({
utd: utd.UniformDataType.HYPERLINK,
content: 'https://www.vmall.com/index.html?cid=128688',
title: 'Huawei Vmall',
description: 'Phone',
label: 'Huawei Vmall',
// ...
});
} catch (error) {
hilog.error(DOMAIN, 'testTag', `addRecord error. Code: ${error?.code}, message: ${error?.message}`);
} [h2]getRecords
getRecords(): Array<SharedRecord>
Obtains all data records of the current shared data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Returns:
| Type | Description |
| Array<SharedRecord> | All records contained in the current SharedData object. |
Example:
aboutToAppear(): void {
systemShare.getSharedData(this.want).then((data: systemShare.SharedData) => {
let records: systemShare.SharedRecord[] = data.getRecords();
records.forEach(async (record: systemShare.SharedRecord) => {
// ...
});
}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `getSharedData error. Code: ${error?.code}, message: ${error?.message}`);
});
} ShareController
The display mode of the sharing panel varies according to devices. Different preview modes and sharing methods are provided for apps based on screen specifications and parameters.
-
On phones and TVs, the sharing panel is displayed in modal mode by default. When phones are in landscape or unfolded mode, the sharing panel is displayed as a dialog box.
-
On PCs, 2-in-1 devices, and tablets, the sharing panel is displayed in pop-up mode, which requires the anchor information to be passed.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
[h2]constructor
constructor(data: SharedData)
A constructor used to create the sharing panel.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| data | SharedData | Yes | Shared data. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.HYPERLINK,
content: 'https://www.vmall.com/index.html?cid=128688',
title: 'Huawei Vmall',
description: 'Phone',
});
let controller: systemShare.ShareController = new systemShare.ShareController(shareData); [h2]show
show(context: common.UIAbilityContext, options: ShareControllerOptions): Promise<void>
Displays the sharing panel. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
Returns:
| Type | Description |
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and Share Kit Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
| 1003702001 | Record types are not support. (The batch and multiple selection modes support { @link UDMF.File } type records only.) |
| 1003702002 | IPC data is oversized. |
Example:
@Component
export default struct LinkScenario {
private async share() {
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.HYPERLINK,
content: 'https://www.vmall.com/index.html?cid=128688',
title: 'Huawei Vmall',
description: 'Phone',
});
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
const uiContext: UIContext = this.getUIContext();
const context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
controller.show(context, {
selectionMode: systemShare.SelectionMode.SINGLE,
previewMode: systemShare.SharePreviewMode.DEFAULT,
}).then(() => {
hilog.info(DOMAIN, 'testTag', 'ShareController show success.');
}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `ShareController show error. code: ${error?.code}, message: ${error?.message}`);
});
}
// ...
} [h2]on('dismiss')
on(event: 'dismiss', callback: () => void): void
Registers a listener for sharing panel closing events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| event | string | Yes | Event callback type. The supported event is dismiss. This event is triggered when the sharing panel is closed. |
| callback | () => void | Yes | Event callback. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
private async handelShareDismiss(): Promise<void> {
const uiContext: UIContext = this.getUIContext();
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.PLAIN_TEXT,
content: 'Hello HarmonyOS',
});
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
const context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
const callback = () => {
try {
hilog.info(DOMAIN, 'testTag', 'HuaweiShare_ dismiss invoked.');
uiContext.getPromptAction().showToast({ message: 'dismiss' });
} catch (error) {
hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
}
};
controller.on('dismiss', callback);
controller.show(context, {
previewMode: systemShare.SharePreviewMode.DEFAULT,
selectionMode: systemShare.SelectionMode.SINGLE,
}).then(() => {
hilog.info(DOMAIN, 'testTag', 'HuaweiShare_ show');
}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `HuaweiShare_ show error. Code: ${error?.code}, message: ${error?.message}`);
});
} [h2]off('dismiss')
off(event: 'dismiss', callback: () => void): void
Unregisters a listener for sharing panel closing events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| event | string | Yes | Event callback type. The supported event is dismiss. It is used to unregister a listener for sharing panel closing events. |
| callback | () => void | Yes | Callback function. You can pass the callback used in the on API to unregister the corresponding listener. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
private async handelShareDisableDismiss(): Promise<void> {
const uiContext: UIContext = this.getUIContext();
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.PLAIN_TEXT,
content: 'Hello HarmonyOS',
});
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
const context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
const callback = () => {
try {
hilog.info(DOMAIN, 'testTag', 'HuaweiShare_ dismiss invoked.');
uiContext.getPromptAction().showToast({ message: 'dismiss' });
} catch (error) {
hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
}
};
controller.on('dismiss', callback);
controller.off('dismiss', callback);
} [h2]on('shareCompleted')
on(type: 'shareCompleted', callback: Callback<ShareOperationResult>): void
Registers a listener for user sharing completion events. The sharing channel, which can be used for data statistics, is returned. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.1.0(18)
Parameters:
| Parameter | Type | Mandatory | Description |
| type | string | Yes | Event callback type. The supported event is shareCompleted, which is triggered when a user completes sharing. |
| callback | Callback<ShareOperationResult> | Yes | Event callback. You can obtain the sharing channel through the callback parameter. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
private async handelShareCompleted(): Promise<void> {
const uiContext: UIContext = this.getUIContext();
const contextFaker: Context = uiContext.getHostContext() as Context;
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);
const context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
const callback = (result: systemShare.ShareOperationResult) => {
hilog.info(DOMAIN, 'testTag', `HuaweiShare_ shareCompleted invoked. result: ${result.targetAbilityInfo.name}`);
};
controller.on('shareCompleted', callback);
controller.show(context, {
previewMode: systemShare.SharePreviewMode.DETAIL,
selectionMode: systemShare.SelectionMode.SINGLE,
}).then(() => {
hilog.info(DOMAIN, 'testTag', 'HuaweiShare_ show');
}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `HuaweiShare_ show error. Code: ${error?.code}, message: ${error?.message}`);
});
} [h2]off('shareCompleted')
off(type: 'shareCompleted', callback?: Callback<ShareOperationResult>): void
Unregisters a listener for user sharing completion events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.1.0(18)
Parameters:
| Parameter | Type | Mandatory | Description |
| type | string | Yes | Event callback type. The supported event is shareCompleted. It is used to unregister a listener for sharing panel closing events. |
| callback | Callback<ShareOperationResult> | No | Callback function. You can pass the callback used in the on API to unregister the corresponding listener. If you do not pass the callback, you will unregister all listeners. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
Example:
private async handelShareDisableCompleted(): Promise<void> {
const uiContext: UIContext = this.getUIContext();
const contextFaker: Context = uiContext.getHostContext() as Context;
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);
const context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
const callback = (result: systemShare.ShareOperationResult) => {
hilog.info(DOMAIN, 'testTag', `HuaweiShare_ shareCompleted invoked. result: ${result.targetAbilityInfo.name}`);
};
controller.on('shareCompleted', callback);
controller.off('shareCompleted', callback);
} getSharedData
getSharedData(want: Want): Promise<SharedData>
Parses shared data from want obtained by the target app. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
| want | Want | Yes | want information obtained by the target app. |
Returns:
| Type | Description |
| Promise<SharedData> | Promise used to return the shared data. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and Share Kit Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
| 1003703001 | Parse data failed. |
Example:
aboutToAppear(): void {
systemShare.getSharedData(this.want).then((data: systemShare.SharedData) => {
let records: systemShare.SharedRecord[] = data.getRecords();
records.forEach(async (record: systemShare.SharedRecord) => {
switch (true) {
case this.belongsToImage(record.utd):
record.uri && (this.imageUri = record.uri);
break;
default:
break;
}
});
}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `getSharedData error. Code: ${error?.code}, message: ${error?.message}`);
});
} getWant
getWant(data: SharedData, options?: ShareControllerOptions): Promise<Want>
Constructs the want data based on SharedData and the preview mode. This API uses a promise to return the result.
Do not arbitrarily modify parameters in the returned want data, as this may lead to unknown errors.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.SystemShare
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
| data | SharedData | Yes | Data to be shared to the target app. |
| options | ShareControllerOptions | No | Sharing controller configuration items. |
Returns:
| Type | Description |
| Promise<Want> | Promise used to return the want information to be shared to the target app. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and Share Kit Error Codes.
| ID | Error Message |
| 401 | Parameter error. |
| 1003703001 | Parse data failed. |
Example:
Preview mode not configured
onSessionCreate(): void {
let data: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.PLAIN_TEXT,
content: 'Hello HarmonyOS'
});
data.addRecord({
utd: utd.UniformDataType.PNG,
uri: 'file://.../test.png'
});
systemShare.getWant(data)
.then((want) => {
})
.catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `Failed to getWant. Code: ${error?.code}, message: ${error?.message}`);
});
} Preview mode configured
onSessionCreatePreview(): void {
let data: systemShare.SharedData = new systemShare.SharedData({
utd: utd.UniformDataType.PLAIN_TEXT,
content: 'Hello HarmonyOS'
});
data.addRecord({
utd: utd.UniformDataType.PNG,
uri: 'file://.../test.png'
});
let options : systemShare.ShareControllerOptions = {
previewMode: systemShare.SharePreviewMode.DETAIL,
selectionMode: systemShare.SelectionMode.SINGLE
};
systemShare.getWant(data, options)
.then((want) => {
})
.catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', `Failed to getWant. Code: ${error?.code}, message: ${error?.message}`);
});
}