目录

harmonyShare (Huawei Share)

This module provides Huawei Share event registration.

Model restriction: APIs of this module can be used only in the stage model.

Since: 5.0.0(12)

Modules to Import

import { harmonyShare } from '@kit.ShareKit';

SharableErrorCode

Reason for rejecting a sharing callback. The user will be informed of the reason through a system notification.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 5.0.3(15)

Name Value Description
NO_CONTENT_ERROR 1 Used when no content is shared.
NO_INTERNET_ERROR 2 Used when there is no network connection available.
DOWNLOAD_ERROR 3 Used when download fails.

ReceivableErrorCode

Reason for rejecting a callback for receiving data in sandbox mode. The user will be informed of the reason through a system notification.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Value Description
NO_RECEIVABLE_ERROR 1 Used when data cannot be received.

ShareResultCode

Result for data reception in the sandbox (success or cause of failure).

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Value Description
SHARE_SUCCESS 0 Data received successfully in the sandbox.
SEND_FAILED 1 Data transfer failed.
CANCEL_BY_SENDER 2 The sender canceled the sending.
CANCEL_BY_RECEIVER 3 The receiver canceled the reception.

SharableTarget

Callback parameter after a Huawei Share event is triggered. This parameter can be used for cross-device sharing.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 5.0.0(12)

[h2]share

share(data: systemShare.SharedData): Promise<void>

Shares data across devices. 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.HarmonyShare

Since: 5.0.0(12)

Parameters:

Parameter Type Mandatory Description
data systemShare.SharedData Yes Shared data.

Returns:

Type Description
Promise<void> Promise that returns no value.

Error codes:

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

ID Error Message
401 Parameter error.

Example:

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

// Register a knockShare event listener.
harmonyShare.on('knockShare', (sharableTarget: harmonyShare.SharableTarget) => {
  // Construct the data to be shared.
  let shareData: systemShare.SharedData = new systemShare.SharedData({
    utd: utd.UniformDataType.PLAIN_TEXT,
    content: 'This is a piece of text.'
  });
  // Initiate sharing.
  sharableTarget.share(shareData);
});

[h2]reject

reject(error: SharableErrorCode): Promise<void>

Rejects a sharing that cannot proceed for any reason upon receiving a callback. 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.HarmonyShare

Since: 5.0.3(15)

Parameters:

Parameter Type Mandatory Description
error SharableErrorCode Yes Reason for rejecting the sharing. The user will be informed of the reason through a system message.

Returns:

Type Description
Promise<void> Promise that returns no value.

Error codes:

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

ID Error Message
401 Parameter error.

Example:

import { harmonyShare } from '@kit.ShareKit';

// Register a knockShare event listener.
harmonyShare.on('knockShare', (sharableTarget: harmonyShare.SharableTarget) => {
  // Reject the sharing.
  sharableTarget.reject(harmonyShare.SharableErrorCode.NO_CONTENT_ERROR);
});

[h2]updateShareData

updateShareData(data: UpdatedData): Promise<void>

Updates the preview image before the shared data is sent. This API uses a promise to return the result.

This API is only used for the Tap to Transfer feature.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
data UpdatedData Yes Target data for the update.

Returns:

Type Description
Promise<void> Promise that returns no value.

Example:

import { harmonyShare } from '@kit.ShareKit';
import { fileUri } from '@kit.CoreFileKit';

// Register a knockShare event listener.
harmonyShare.on('knockShare', (sharableTarget: harmonyShare.SharableTarget) => {
  const uiContext: UIContext = this.getUIContext();
  const contextFaker: Context = uiContext.getHostContext() as Context;
  let updatedData: harmonyShare.UpdatedData = {
    thumbnailUri: fileUri.getUriFromPath(contextFaker.filesDir + '/exampleImage.jpg')
  };
  // Update the preview image.
  sharableTarget.updateShareData(updatedData);
});

[h2]clarifyNonShare

clarifyNonShare(info: SharableErrorInfo): Promise<void>

Notifies the user that no sharable content is available on the current page and provides appropriate guidance. This API uses a promise to return the result.

This API is only used for the Tap to Transfer feature.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.2(22)

Parameters:

Parameter Type Mandatory Description
info SharableErrorInfo Yes Message used to notify the user of the reason why the sharing is unavailable.

Returns:

Type Description
Promise<void> Promise that returns no value.

Example:

import { harmonyShare } from '@kit.ShareKit';

// Register a knockShare event listener.
harmonyShare.on('knockShare', (sharableTarget: harmonyShare.SharableTarget) => {
  // Prompt that no content is shared.
  sharableTarget.clarifyNonShare({ message: 'Try again on a page that supports Tap to Transfer.' });
});

[h2]getInfo

getInfo(): SharableTargetInfo

Obtains information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the sender.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 26.0.0

Returns:

Type Description
SharableTargetInfo Information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the sender, such as the coordinates of the position where the screen is tapped.

Example:

import { harmonyShare } from '@kit.ShareKit';

// Register a knockShare event listener.
harmonyShare.on('knockShare', (sharableTarget: harmonyShare.SharableTarget) => {
  // Obtain the coordinates when the screen is tapped.
  let sharableTargetInfo = sharableTarget.getInfo();
  console.info('screenX is:', sharableTargetInfo.coordinate?.screenX);
  console.info('screenY is:', sharableTargetInfo.coordinate?.screenY);
});

ReceivableTarget

Parameter in the callback for receiving data in sandbox mode.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

[h2]receive

receive(receiveUri: string, callback: ReceiveCallback): Promise<void>

Provides the URI of the sandbox directory for receiving data. The received files are saved to this directory. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
receiveUri string Yes

Directory for storing data received by the sandbox. The directory must exist.

Note: Share Kit will obtain authorization for this directory before the transfer starts and automatically revoke the authorization after the transfer is complete. You are advised to use an existing empty directory to ensure information security.

callback ReceiveCallback Yes Callback for receiving data in sandbox mode.

Returns:

Type Description
Promise<void> Promise that returns no value.

Example:

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

let capabilityRegistry: harmonyShare.RecvCapabilityRegistry = {
  windowId: 999, // This is only an example. Replace it with the correct window ID.
  capabilities: [{
    utd: utd.UniformDataType.IMAGE,
    maxSupportedCount: 1
  }]
}
// Register a dataReceive event listener.
harmonyShare.on('dataReceive', capabilityRegistry, (receivableTarget: harmonyShare.ReceivableTarget) => {
  let uiContext: UIContext = this.getUIContext();
  let context = uiContext.getHostContext() as common.UIAbilityContext;
  receivableTarget.receive(context.filesDir, { // This is only an example. Replace it with the actual path.
    onDataReceived: (sharedData: systemShare.SharedData) => {
      let sharedRecords = sharedData.getRecords();
      sharedRecords.forEach((record: systemShare.SharedRecord) => {
        // Process the shared data.
      });
    },
    onResult(resultCode: harmonyShare.ShareResultCode) {
      if (resultCode === harmonyShare.ShareResultCode.SHARE_SUCCESS) {
        // To do things.
      }
    }
  });
});

[h2]reject

reject(error: ReceivableErrorCode): Promise<void>

Rejects a sharing if data reception cannot proceed for any reason upon receiving a callback. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
error ReceivableErrorCode Yes Reason for rejecting data reception in sandbox mode. The user will be informed of the reason through a system message.

Returns:

Type Description
Promise<void> Promise that returns no value.

Example:

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

let capabilityRegistry: harmonyShare.RecvCapabilityRegistry = {
  windowId: 999, // This is only an example. Replace it with the correct window ID.
  capabilities: [{
    utd: utd.UniformDataType.IMAGE,
    maxSupportedCount: 1
  }]
}
// Register a dataReceive event listener.
harmonyShare.on('dataReceive', capabilityRegistry, (receivableTarget: harmonyShare.ReceivableTarget) => {
  receivableTarget.reject(harmonyShare.ReceivableErrorCode.NO_RECEIVABLE_ERROR);
});

[h2]getInfo

getInfo(): ReceivableTargetInfo

Obtains information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the receiver.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 26.0.0

Returns:

Type Description
ReceivableTargetInfo Information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the receiver, such as the coordinates of the position where the screen is tapped.

Example:

import { uniformTypeDescriptor as utd } from '@kit.ArkData';
import { systemShare, harmonyShare } from '@kit.ShareKit';
import { common } from '@kit.AbilityKit';
import { fileUri } from '@kit.CoreFileKit';

let capabilityRegistry: harmonyShare.RecvCapabilityRegistry = {
  windowId: 999, // This is only an example. Replace it with the correct window ID.
  capabilities: [{
    utd: utd.UniformDataType.IMAGE,
    maxSupportedCount: 1
  }]
}
// Register a dataReceive event listener.
harmonyShare.on('dataReceive', capabilityRegistry, (receivableTarget: harmonyShare.ReceivableTarget) => {
  let uiContext: UIContext = this.getUIContext();
  let context = uiContext.getHostContext() as common.UIAbilityContext;
  let sandboxUri = fileUri.getUriFromPath(context.filesDir);
  let receivableTargetInfo = receivableTarget.getInfo();
  console.info('screenX is:', receivableTargetInfo.coordinate?.screenX);
  console.info('screenY is:', receivableTargetInfo.coordinate?.screenY);
  receivableTarget.receive(sandboxUri, {
    onDataReceived: (sharedData: systemShare.SharedData) => {
      let sharedRecords = sharedData.getRecords();
      sharedRecords.forEach((record: systemShare.SharedRecord) => {
        // Process the shared data.
      });
    },
    onResult(resultCode: harmonyShare.ShareResultCode) {
      if (resultCode === harmonyShare.ShareResultCode.SHARE_SUCCESS) {
        // To do things.
      }
    }
  });
});

UpdatedData

Data sent by the Huawei Share event.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
thumbnailUri string No Yes URI of a preview image.

BaseCapabilityRegistry

Basic configuration for Huawei Share event registration.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
windowId number No No Window ID.

SendCapabilityRegistry

Window registration configuration item for the Huawei Share event. This API is inherited from BaseCapabilityRegistry.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
sendOnly boolean No Yes

Indicates whether only data sending is supported. The default value is false, indicating that data sending and reception are both supported. If this parameter is set to true for both devices, two-way sharing is not allowed.

Note: This API is only used for the Tap to Transfer feature.

RecvCapability

Sets the data reception capability for the sandbox, including the file types and the maximum number of files that can be received at a time.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

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).
maxSupportedCount number No No Maximum number of files that can be received at a time. The value must be a positive integer.

RecvCapabilityRegistry

Window registration configuration item for the event of receiving data in sandbox mode. This API is inherited from BaseCapabilityRegistry.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
capabilities RecvCapability[] No No Data reception capability of the sandbox, including the supported data types and quantity that can be received at a time.

TransferBaseResults

Callback function for file transfer completion when the sandbox receives files.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
onResult Callback<ShareResultCode> No Yes Callback function for file transfer completion. It is used to notify the transfer result.

ReceiveCallback

Callback function triggered when the sandbox completes file receiving. It can be used to listen for the completion event and process the received data. This API is inherited from TransferBaseResults.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.0(20)

Name Type Read-Only Optional Description
onDataReceived Callback<systemShare.SharedData> No No Callback function triggered when the sandbox completes file receiving. It is used to provide the list of files saved to the sandbox path.

SharableErrorInfo

Message used to notify the user of the reason why the sharing is unavailable.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 6.0.2(22)

Name Type Read-Only Optional Description
message string No Yes Message content.

CoordinateInfo

Coordinates of the position where the screen is tapped when the Tap to Transfer event is triggered between a phone and a PC/2-in-1 device or a tablet.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 26.0.0

Name Type Read-Only Optional Description
screenX number No No X coordinate with the upper left corner of the screen as the origin when a Tap to Transfer event is triggered. The value can only be set to an integer. The unit is px.
screenY number No No Y coordinate with the upper left corner of the screen as the origin when a Tap to Transfer event is triggered. The value can only be set to an integer. The unit is px.

SharableTargetInfo

Information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the sender.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 26.0.0

Name Type Read-Only Optional Description
coordinate CoordinateInfo No Yes Coordinates of the position where the screen is tapped when the Tap to Transfer event is triggered.

ReceivableTargetInfo

Information about the Tap to Transfer event triggered by a PC/2-in-1 device or a tablet as the receiver.

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

System capability: SystemCapability.Collaboration.HarmonyShare

Since: 26.0.0

Name Type Read-Only Optional Description
coordinate CoordinateInfo No Yes Coordinates of the position where the screen is tapped when the Tap to Transfer event is triggered.

on('knockShare')

on(event: 'knockShare', callback: Callback<SharableTarget>): void

Registers a device tapping event listener. 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.HarmonyShare

Since: 5.0.0(12)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is knockShare, indicating that the event is triggered by tapping devices together.
callback Callback<SharableTarget> Yes Callback used to return the sharing sending object, which is used to send the shared content.

Error codes:

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

ID Error Message
401 Parameter error.

Example:

private tipsListening() {
  if (!this.tipsStatus) {
    harmonyShare.on('knockShare', this.sendOnlyCallback);
    this.tipsStatus = true;
  } else {
    try {
      const uiContext: UIContext = this.getUIContext();
      uiContext.getPromptAction().showToast({ message: $r('app.string.knock_close_other') });
    } catch (error) {
      hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
    }
  }
}

off('knockShare')

off(event: 'knockShare', callback?: Callback<SharableTarget>): void

Unregisters a device tapping event listener. 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.HarmonyShare

Since: 5.0.0(12)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is knockShare, indicating that the device tapping event listener is unregistered.
callback Callback<SharableTarget> 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 tipsDisablingListening() {
  harmonyShare.off('knockShare', this.sendOnlyCallback);
  this.tipsStatus = true;
}

on('knockShare')

on(event: 'knockShare', capability: SendCapabilityRegistry, callback: Callback<SharableTarget>): void

Registers a device tapping event listener. You are advised to use this method on PCs/2-in-1 devices and tablets and set the windowId parameter to specify the window that can be tapped. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is knockShare, indicating that the event is triggered by tapping devices together.
capability SendCapabilityRegistry Yes Event attribute.
callback Callback<SharableTarget> Yes Callback used to return the sharing sending object, which is used to send the shared content.

Example:

private sendOnlyListening() {
  if (!this.sendOnlyStatus) {
    if (this.windowId) {
      let capabilityRegistry: harmonyShare.SendCapabilityRegistry = {
        windowId: this.windowId,
        sendOnly: true,
      }
      harmonyShare.on('knockShare', capabilityRegistry, this.sendOnlyCallback);
      this.sendOnlyStatus = true;
    }
  } else {
    try {
      const uiContext: UIContext = this.getUIContext();
      uiContext.getPromptAction().showToast({ message: $r('app.string.knock_close_other') });
    } catch (error) {
      hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
    }
  }
}

off('knockShare')

off(event: 'knockShare', capability: SendCapabilityRegistry, callback?: Callback<SharableTarget>): void

Unregisters a device tapping event listener. You are advised to use this method on PCs/2-in-1 devices and tablets and set the windowId parameter to specify the window that can be tapped. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is knockShare, indicating that the device tapping event listener is unregistered.
capability SendCapabilityRegistry Yes Event attribute.
callback Callback<SharableTarget> 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.

Example:

private sendOnlyDisablingListening() {
  if (this.windowId) {
    let capabilityRegistry: harmonyShare.SendCapabilityRegistry = {
      windowId: this.windowId,
      sendOnly: true,
    }
    harmonyShare.off('knockShare', capabilityRegistry, this.sendOnlyCallback);
    this.sendOnlyStatus = false;
  }
}

on('gesturesShare')

on(event: 'gesturesShare', callback: Callback<SharableTarget>): void

Registers a Grab & drop event listener. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is gesturesShare, indicating that the event is triggered by clenching the fist.
callback Callback<SharableTarget> Yes Callback used to return the sharing sending object, which is used to send the shared content.

Example:

private immersiveListening() {
  if (this.isNoListening()) {
    harmonyShare.on('gesturesShare', this.immersiveCallback);
    this.immersiveStatus = true;
  } else {
    try {
      const uiContext: UIContext = this.getUIContext();
      uiContext.getPromptAction().showToast({ message: $r('app.string.gesture_close_other') });
    } catch (error) {
      hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
    }
  }
}

off('gesturesShare')

off(event: 'gesturesShare', callback?: Callback<SharableTarget>): void

Unregisters a Grab & drop event listener. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is gesturesShare, indicating that the Grab & drop event listener is unregistered.
callback Callback<SharableTarget> 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.

Example:

private immersiveDisablingListening() {
  harmonyShare.off('gesturesShare', this.immersiveCallback);
  this.immersiveStatus = false;
}

on('gesturesShare')

on(event: 'gesturesShare', capability: SendCapabilityRegistry, callback: Callback<SharableTarget>): void

Registers a Grab & drop event listener. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is gesturesShare, indicating that the event is triggered by clenching the fist.
capability SendCapabilityRegistry Yes Event attribute.
callback Callback<SharableTarget> Yes Callback used to return the sharing sending object, which is used to send the shared content.

Example:

private purityListening() {
  if (this.isNoListening()) {
    if (this.windowId) {
      let capabilityRegistry: harmonyShare.SendCapabilityRegistry = {
        windowId: this.windowId,
      }
      harmonyShare.on('gesturesShare', capabilityRegistry, this.purityCallback);
      this.purityStatus = true;
    }
  } else {
    try {
      const uiContext: UIContext = this.getUIContext();
      uiContext.getPromptAction().showToast({ message: $r('app.string.gesture_close_other') });
    } catch (error) {
      hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
    }
  }
}

off('gesturesShare')

off(event: 'gesturesShare', capability: SendCapabilityRegistry, callback?: Callback<SharableTarget>): void

Unregisters a Grab & drop event listener. 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.HarmonyShare

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is gesturesShare, indicating that the Grab & drop event listener is unregistered.
capability SendCapabilityRegistry Yes Event attribute.
callback Callback<SharableTarget> 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.

Example:

private purityDisablingListening() {
  if (this.windowId) {
    let capabilityRegistry: harmonyShare.SendCapabilityRegistry = {
      windowId: this.windowId,
    }
    harmonyShare.off('gesturesShare', capabilityRegistry, this.purityCallback);
    this.purityStatus = false;
  }
}

on('dataReceive')

on(event: 'dataReceive', capability: RecvCapabilityRegistry, callback: Callback<ReceivableTarget>): void

Registers an event listener for receiving data in sandbox mode. Only file data is supported. The original receiving logic is retained for text data (including links). 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.HarmonyShare

Device behavior differences: For API version 6.0.2(22) and earlier, this API is supported on PCs and 2-in-1 devices. On other device types, it returns error code 801. Since API version 6.1.0(23), this API is supported on PCs, 2-in-1 devices, and tablets, but does not respond on other device types.

Since: 6.0.0(20)

Parameters:

Parameter Type Mandatory Description
event string Yes Event callback type. The value is dataReceive, which is triggered when a phone lightly touches a PC, 2-in-1, or tablet device screen.
capability RecvCapabilityRegistry Yes Event attribute.
callback Callback<ReceivableTarget> Yes Callback used to return the sharing receiving object, which is used to receive the shared content.

Example:

private dataReceiveCallback = (receivableTarget: harmonyShare.ReceivableTarget) => {
  let uiContext: UIContext = this.getUIContext();
  let context = uiContext.getHostContext() as common.UIAbilityContext;
  let sandboxUri = fileUri.getUriFromPath(context.filesDir);
  receivableTarget.receive(sandboxUri, {
    onDataReceived: (sharedData: systemShare.SharedData) => {
      let sharedRecords = sharedData.getRecords();
      sharedRecords.forEach((record: systemShare.SharedRecord) => {
        this.dataReceiveUri = record.uri;
      });
    },
    onResult: (resultCode: harmonyShare.ShareResultCode) => {
      if (resultCode === harmonyShare.ShareResultCode.SHARE_SUCCESS) {
        try {
          const uiContext: UIContext = this.getUIContext();
          uiContext.getPromptAction().showToast({ message: $r('app.string.success_supported') });
        } catch (error) {
          hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
        }
      }
    }
  });
}

private isNoListening() {
  return !this.dataReceiveStatus;
}

private dataReceiveListening() {
  if (this.isNoListening()) {
    if (this.windowId) {
      let capabilityRegistry: harmonyShare.RecvCapabilityRegistry = {
        windowId: this.windowId,
        capabilities: [{
          utd: utd.UniformDataType.IMAGE,
          maxSupportedCount: 1,
        }]
      }
      harmonyShare.on('dataReceive', capabilityRegistry, this.dataReceiveCallback);
      this.dataReceiveStatus = true;
    }
  } else {
    try {
      const uiContext: UIContext = this.getUIContext();
      uiContext.getPromptAction().showToast({ message: $r('app.string.knock_close_other') });
    } catch (error) {
      hilog.error(DOMAIN, 'testTag', `showToast error. Code: ${error?.code}, message: ${error?.message}`);
    }
  }
}

off('dataReceive')

off(event: 'dataReceive', capability: RecvCapabilityRegistry, callback?: Callback<ReceivableTarget>): void

Unregisters an event listener for receiving data in sandbox mode. 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.HarmonyShare

Device behavior differences: For API version 6.0.2(22) and earlier, this API is supported on PCs and 2-in-1 devices. On other device types, it returns error code 801. Since API version 6.1.0(23), this API is supported on PCs, 2-in-1 devices, and tablets, but does not respond on other device types.

Since: 6.0.0(20)

Parameter Type Mandatory Description
event string Yes Event callback type. The value is dataReceive, indicating that the event listener for receiving data in sandbox mode is unregistered.
capability RecvCapabilityRegistry Yes Event attribute.
callback Callback<ReceivableTarget> 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.

Example:

private dataReceiveDisablingListening() {
  try {
    if (this.windowId) {
      let capabilityRegistry: harmonyShare.RecvCapabilityRegistry = {
        windowId: this.windowId,
        capabilities: [{
          utd: utd.UniformDataType.IMAGE,
          maxSupportedCount: 1,
        }]
      }
      harmonyShare.off('dataReceive', capabilityRegistry, this.dataReceiveCallback);
      this.dataReceiveStatus = false;
    }
  } catch (error) {
    hilog.error(DOMAIN, 'testTag', 'error message: %s', error?.message ?? 'unknown error');
  }
}