We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All

systemShare (System Share)

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: This API can be used only in the stage model.

Since: 4.1.0(11)

Modules to Import

PhonePC/2in1TabletTV
import { systemShare } from '@kit.ShareKit';

SharedRecord

PhonePC/2in1TabletTV

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)

Expand
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. Either content or uri must be set.

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: Either content or uri must be set.

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

PhonePC/2in1TabletTV

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)

Expand
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

You can specify the list of target apps that can be shared by configuring the unique app identifier (appIdentifier field) list. Only the first 50 values are effective. The ohos.permission.SET_SYSTEMSHARE_APPLAUNCHTRUSTLIST permission is required. 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.

Since: 6.0.1(21)

ShareControllerAnchor

PhonePC/2in1TabletTV

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.

NOTE

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)

Expand
Name Type Read-Only Optional Description
windowOffset Offset No No Window offset to the anchor.
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

PhonePC/2in1TabletTV

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)

Expand
Name Type Read-Only Optional Description
x number No No X coordinate, in pixels.
y number No No Y coordinate, in pixels.

Size

PhonePC/2in1TabletTV

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)

Expand
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

PhonePC/2in1TabletTV

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)

Expand
Name Type Read-Only Optional Description
targetAbilityInfo ShareAbilityInfo Yes No Information about the sharing channel.

ShareAbilityInfo

PhonePC/2in1TabletTV

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)

Expand
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 ShareAbilityName.

A non-system operation name, which is in [bundleName]#[moduleName]#[abilityName] format.

ContactInfo

PhonePC/2in1TabletTV

Contact information recommended by Intents Kit. When content is shared to a recommended contact, this parameter is passed.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Since: 4.1.0(11)

Expand
Name Type Read-Only Optional Description
contactType string No No Contact type. The value comes from the value of entityName in the data provided by an app to Intents Kit, for example, Contact or ChatGroup.
contactId string No No Contact ID. The value comes from the value of entityId in the data provided by an app to Intents Kit.

RevisitShareRecordData

PhonePC/2in1TabletTV

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:

Expand
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

PhonePC/2in1TabletTV

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:

Expand
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

PhonePC/2in1TabletTV

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)

Expand
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

PhonePC/2in1TabletTV

Selection mode.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Since: 4.1.0(11)

Expand
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

PhonePC/2in1TabletTV

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)

Expand
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

PhonePC/2in1TabletTV

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)

Expand
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

PhonePC/2in1TabletTV

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)

Expand
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

PhonePC/2in1TabletTV

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)

Expand
Name Value Description
READING_SHARE 1 Type of the reading shared data.

ReadingShareRecordStyle

PhonePC/2in1TabletTV

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)

Expand
Name Value Description
STYLE_HIGHLIGHT_CONTENT 0 Highlight the selected text. This is the default value.
STYLE_HIGHLIGHT_TITLE 1 Highlight the title.

SharedData

PhonePC/2in1TabletTV

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.

NOTE

A SharedData object supports a maximum of 500 data records, with a total size limit of 200 KB due to IPC transmission constraints.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Since: 4.1.0(11)

constructor

PhonePC/2in1TabletTV

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:

Expand
Parameter Type Mandatory Description
record SharedRecord Yes Shared data record.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

let data: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PLAIN_TEXT,
  content: 'Hello HarmonyOS'
});

addRecord

PhonePC/2in1TabletTV

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:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.
1003700001 The number of records exceeds the maximum.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

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'
});

getRecords

PhonePC/2in1TabletTV

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:

Expand
Type Description
Array<SharedRecord> All records contained in the current SharedData object.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

let data: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PLAIN_TEXT,
  content: 'Hello HarmonyOS'
});

let records: systemShare.SharedRecord[] = data.getRecords();
records.forEach((record: systemShare.SharedRecord) => {
  // To do things.
});

ShareController

PhonePC/2in1TabletTV

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, 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 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)

constructor

PhonePC/2in1TabletTV

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:

Expand
Parameter Type Mandatory Description
data SharedData Yes Shared data.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

let data: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PLAIN_TEXT,
  content: 'Hello HarmonyOS'
});

let controller: systemShare.ShareController = new systemShare.ShareController(data);

show

PhonePC/2in1TabletTV

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:

Expand
Parameter Type Mandatory Description
context

common.UIAbilityContext

Yes Context object for starting the sharing panel.
options ShareControllerOptions Yes Sharing controller configuration items.

Returns:

Expand
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.

Expand
Error Code 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:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Component
export struct ShareUtdText {
  build() {
  }

  private share() {
    // Construct ShareData. You need to configure a valid data record.
    let shareData: systemShare.SharedData = new systemShare.SharedData({
      utd: utd.UniformDataType.TEXT,
      content: 'This is a piece of text.'
    });
    // Display the sharing panel.
    let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
    let uiContext: UIContext = this.getUIContext();
    let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
    controller.show(context, {
      selectionMode: systemShare.SelectionMode.SINGLE,
      previewMode: systemShare.SharePreviewMode.DETAIL
    }).then(() => {
      console.info('ShareController show success.');
    }).catch((error: BusinessError) => {
      console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
    });
  }
}

on('dismiss')

PhonePC/2in1TabletTV

on(event: 'dismiss', callback: () => void): void

Registers a listener for sharing panel closing events.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Since: 4.1.0(11)

Parameters:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

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 controller: systemShare.ShareController = new systemShare.ShareController(data);
controller.on('dismiss', () => {
  console.info('Share panel closed');
});

off('dismiss')

PhonePC/2in1TabletTV

off(event: 'dismiss', callback: () => void): void

Unregisters a listener for sharing panel closing events.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Since: 4.1.0(11)

Parameters:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

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 controller: systemShare.ShareController = new systemShare.ShareController(data);
let callback = () => {
  console.info('Share panel closed');
};
controller.on('dismiss', callback);
controller.off('dismiss', callback);

on('shareCompleted')

PhonePC/2in1TabletTV

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.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Device behavior differences: This API has no effect on TVs, but works properly on other devices.

Since: 5.1.0(18)

Parameters:

Expand
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.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

let data: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PLAIN_TEXT,
  content: 'Hello HarmonyOS'
});

let controller: systemShare.ShareController = new systemShare.ShareController(data);
controller.on('shareCompleted', (result: systemShare.ShareOperationResult) => {
  console.info('shareCompleted name:', result.targetAbilityInfo.name);
});

off('shareCompleted')

PhonePC/2in1TabletTV

off(type: 'shareCompleted', callback?: Callback<ShareOperationResult>): void

Unregisters a listener for user sharing completion events.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Collaboration.SystemShare

Device behavior differences: This API has no effect on TVs, but works properly on other devices.

Since: 5.1.0(18)

Parameters:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.

Example:

import { systemShare } from '@kit.ShareKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';

let data: systemShare.SharedData = new systemShare.SharedData({
  utd: utd.UniformDataType.PLAIN_TEXT,
  content: 'Hello HarmonyOS'
});

let controller: systemShare.ShareController = new systemShare.ShareController(data);
let callback = (result: systemShare.ShareOperationResult) => {
  console.info('shareCompleted name:', result.targetAbilityInfo.name);
};
controller.on('shareCompleted', callback);
controller.off('shareCompleted', callback);

getSharedData

PhonePC/2in1TabletTV

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:

Expand
Parameter Type Mandatory Description
want Want Yes want information obtained by the target app.

Returns:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.
1003703001 Parse data failed.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { Want, ShareExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';

export default class TestShareAbility extends ShareExtensionAbility {
  onSessionCreate(want: Want, session: UIExtensionContentSession) {
    systemShare.getSharedData(want)
      .then((data: systemShare.SharedData) => {
        data.getRecords().forEach((record: systemShare.SharedRecord) => {
          // Process the shared data.
        });
        session.loadContent('pages/Index');
      })
      .catch((error: BusinessError) => {
        console.error(`Failed to getSharedData. Code: ${error.code}, message: ${error.message}`);
        session.terminateSelf();
      });
  }
}

getContactInfo

PhonePC/2in1TabletTV

getContactInfo(want: Want): Promise<ContactInfo>

Parses contact information 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:

Expand
Parameter Type Mandatory Description
want Want Yes want information obtained by the target app.

Returns:

Expand
Type Description
Promise<ContactInfo> Promise used to return contact information.

Error codes:

For details about the error codes, please refer to Universal Error Codes and Share Kit Error Codes.

Expand
Error Code Error Message
401 Parameter error.
1003703001 Parse data failed.

Example:

import { BusinessError } from '@kit.BasicServicesKit';
import { Want, ShareExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';

export default class TestShareAbility extends ShareExtensionAbility {
  onSessionCreate(want: Want, session: UIExtensionContentSession) {
    systemShare.getContactInfo(want)
      .then(async (contact: systemShare.ContactInfo) => {
        // Process contact information. The target users can be specified based on contact type (such as individual or group) and contact ID.
        // Obtain the shared data.
        let data = await systemShare.getSharedData(want);
      })
      .catch((error: BusinessError) => {
        console.error(`Failed to getContactInfo. Code: ${error.code}, message: ${error.message}`);
        // The contact does not exist or an exception occurs when obtaining data.
        session.terminateSelf();
      });
  }
}

getWant

PhonePC/2in1TabletTV

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.

NOTE

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:

Expand
Parameter Type Mandatory Description
data SharedData Yes Data to be shared to the target app.
options ShareControllerOptions No Sharing controller configuration items.

Returns:

Expand
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.

Expand
Error Code Error Message
401 Parameter error.
1003703001 Parse data failed.

Example:

Preview mode not configured

import { BusinessError } from '@kit.BasicServicesKit';
import { Want, ShareExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { systemShare } from '@kit.ShareKit';

export default class TestShareAbility extends ShareExtensionAbility {
  onSessionCreate(want: Want, session: UIExtensionContentSession) {
    // Process the shared data.
    // To do things.
    // Prepare the data to be returned.
    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) => {
        console.info('want = ', JSON.stringify(want));
        session!.terminateSelfWithResult({
          resultCode: 2,
          want: want
        })
      })
      .catch((error: BusinessError) => {
        console.error(`Failed to getWant. Code: ${error.code}, message: ${error.message}`);
      });
  }
}

Preview mode configured

import { BusinessError } from '@kit.BasicServicesKit';
import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { Want, ShareExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';

export default class TestShareAbility extends ShareExtensionAbility {
  onSessionCreate(want: Want, session: UIExtensionContentSession) {
    // Process the shared data.
    // To do things.
    // Prepare the data to be returned.
    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) => {
        console.info('want = ', JSON.stringify(want));
        session!.terminateSelfWithResult({
          resultCode: 2,
          want: want
        })
      })
      .catch((error: BusinessError) => {
        console.error(`Failed to getWant. Code: ${error.code}, message: ${error.message}`);
      });
  }
}
Search in References
Enter a keyword.