openharmony 鸿蒙 js-apis-data-dataShare

2026-08-25 浏览 (1)

@ohos.data.dataShare (DataShare)

The DataShare module allows an application to manage its own data and share data with other applications on the same device.

NOTE

  • The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • The APIs of this module can be used only in the stage model.

Modules to Import

import { dataShare } from '@kit.ArkData';

dataShare.createDataProxyHandle20+

createDataProxyHandle(): Promise<DataProxyHandle>

Creates a DataProxyHandle instance. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Return value

TypeDescription
Promise<DataProxyHandle>Promise used to return the result.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.

Example:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    dataShare.createDataProxyHandle().then((dataProxyHandle) => {
      console.info("createDataProxyHandle succeed");
    }).catch((err: BusinessError) => {
      console.error(`createDataProxyHandle error: code: ${err.code}, message: ${err.message}`);
    });
  };
};

ChangeType20+

Enumerates the data change types.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameValueDescription
INSERT0Data is inserted.
DELETE1Data is deleted.
UPDATE2Data is updated.

ProxyData20+

Defines a struct for shared configurations.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameTypeRead-OnlyOptionalDescription
uristringNoNoUnique ID of a shared configuration, fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application. The value is a string with a maximum of 256 bytes.
valueValueTypeNoYesValue of a shared configuration. If not specified, the value is an empty string. The value is a string with a maximum of 4,096 bytes. If this parameter is not set when the shared configuration is published for the first time, the value will be an empty string by default. If this parameter is not set when a shared configuration is updated, the value of the shared configuration will not be updated.
allowListstring[]NoYesList of applications that can subscribe to and read shared configurations. If this parameter is left empty, the value is an empty string array. The array can contain a maximum of 256 elements. Excess elements are invalid. Each element in the array is the appIdentifier of an application. The maximum length of an appIdentifier is 128 bytes. If the length exceeds 128 bytes, the appIdentifier does not take effect. If this parameter is not set when the shared configuration is published for the first time, the allowlist is empty by default. If this parameter is not set when the shared configuration is updated, the allowlist will not be updated. An empty allowlist indicates that only the publisher can access the shared configuration.

DataProxyChangeInfo20+

Defines a struct for notifying subscribers of the shared configuration changes, including data change type, URI, and content.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameTypeRead-OnlyOptionalDescription
typeChangeTypeNoNoData change type.
uristringNoNoURI to change.
valueValueTypeNoNoChanged data.

DataProxyErrorCode20+

Enumerates the status code returned by the batch operations of shared configuration.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameValueDescription
SUCCESS0The operation is successful.
URI_NOT_EXIST1The URI does not exist or the URI is not subscribed to.
NO_PERMISSION2No permission to perform this operation on the URI.
OVER_LIMIT3The number of configurations published by the current application exceeds the upper limit of 32.

DataProxyResult20+

Defines a struct for the batch operation result of shared configuration.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameTypeRead-OnlyOptionalDescription
uristringNoNoURI to be operated, with a maximum of 256 bytes. The value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application.
resultDataProxyErrorCodeNoNoOperation result code.

DataProxyGetResult20+

Defines a struct for obtaining the batch operation result of shared configuration.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameTypeRead-OnlyOptionalDescription
uristringNoNoURI to be operated, with a maximum of 256 bytes. The value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application.
resultDataProxyErrorCodeNoNoOperation result code.
valueValueType |undefinedNoNoIf the operation is successful, the value is the one set in shared configuration; otherwise, the value is undefined.
allowListstring[] |undefinedNoNoIf the operation is successful, the allowlist is the one set in shared configuration; otherwise, the allowlist is undefined. Only the publisher can obtain the allowlist. Other applications can obtain only the value.

DataProxyType20+

Enumerates the data proxy types.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameValueDescription
SHARED_CONFIG0Inter-application shared configuration.

DataProxyConfig20+

Defines a struct for the data proxy configuration.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

NameTypeRead-OnlyOptionalDescription
typeDataProxyTypeNoNoType of the data proxy.

DataProxyHandle20+

Defines the data proxy handle, which can be used to access or manage shared configuration information. Before calling an API provided by DataProxyHandle, you must create a DataProxyHandle instance using createDataProxyHandle.

on('dataChange')20+

on(event: 'dataChange', uris: string[], config: DataProxyConfig, callback: AsyncCallback<DataProxyChangeInfo[]>): DataProxyResult[]

Subscribes to the change event of the shared configuration corresponding to a specified URI. If the change event is subscribed, the subscriber will receive a callback notification that carries the data change type, changed URI, and changed content when the publisher modifies the configuration. This API uses an asynchronous callback to return the result. This function does not support cross-user notification subscription or subscription to unpublished configurations. If the permission is revoked after the subscription is successful, the subscriber will not be notified consequently.

When the publisher calls the publish or delete API to publish or delete a configuration, a notification is automatically triggered.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Parameters

NameTypeMandatoryDescription
eventstringYesEvent or callback type. The value is dataChange, which indicates the data change. This event is triggered when the publisher modifies the configuration.
urisstring[]YesArray of URIs to be subscribed, with a maximum of 32 URIs. The URI value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application. The value contains a maximum of 256 bytes.
configDataProxyConfigYesData proxy configuration.
callbackAsyncCallback<DataProxyChangeInfo[]>YesCallback triggered when the publisher modifies the configuration.

Return value

TypeDescription
DataProxyResult[]Batch operation result array.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.
15700014The parameter format is incorrect or the value range is invalid.

Example:

const urisToWatch: string[] =
  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
const config: dataShare.DataProxyConfig = {
  type: dataShare.DataProxyType.SHARED_CONFIG,
};
const callback = (err: BusinessError<void>, changes: dataShare.DataProxyChangeInfo[]): void => {
  if (err) {
    console.error('err:', err);
  } else {
    changes.forEach((change) => {
      console.info(`Change Type: ${change.type}, URI: ${change.uri}, Value: ${change.value}`);
    });
  }
};
const results: dataShare.DataProxyResult[] = dataProxyHandle.on('dataChange', urisToWatch, config, callback);
results.forEach((result) => {
  console.info(`URI: ${result.uri}, Result: ${result.result}`);
});

off('dataChange')20+

off(event: 'dataChange', uris: string[], config: DataProxyConfig, callback?: AsyncCallback<DataProxyChangeInfo[]>): DataProxyResult[]

Unsubscribes from the change event of the proxy data corresponding to a specified URI.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Parameters

NameTypeMandatoryDescription
eventstringYesEvent or callback type. The value is dataChange, which indicates the data change.
urisstring[]YesArray of URIs to be unsubscribed, with a maximum of 32 URIs. The URI value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application. The value contains a maximum of 256 bytes.
configDataProxyConfigYesData proxy configuration.
callbackAsyncCallback<DataProxyChangeInfo[]>NoCallback function. If the value is empty, undefined, or null, all notifications of the URIs are unsubscribed.

Return value

TypeDescription
DataProxyResult[]Batch operation result array.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.
15700014The parameter format is incorrect or the value range is invalid.

Example:

const urisToUnWatch: string[] =
  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
const config: dataShare.DataProxyConfig = {
  type: dataShare.DataProxyType.SHARED_CONFIG,
};
const callback = (err: BusinessError<void>, changes: dataShare.DataProxyChangeInfo[]): void => {
  if (err) {
    console.error('err:', err);
  } else {
    changes.forEach((change) => {
      console.info(`Change Type: ${change.type}, URI: ${change.uri}, Value: ${change.value}`);
    });
  }
};
const results: dataShare.DataProxyResult[] = dataProxyHandle.off('dataChange', urisToUnWatch, config, callback);
results.forEach((result) => {
  console.info(`URI: ${result.uri}, Result: ${result.result}`);
});

publish20+

publish(data: ProxyData[], config: DataProxyConfig): Promise<DataProxyResult[]>

Publishes shared configuration items. This API uses a promise to return the result. After shared configuration items are published, the publisher and the applications in the allowlist can access these items. If the URI to be published already exists, the corresponding shared configuration item is updated. If any URI in the configuration item to be published exceeds the maximum length or fails the format verification, the current publish operation fails. Only the publisher can update shared configuration items. Each application supports a maximum of 32 shared configurations.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Parameters

NameTypeMandatoryDescription
dataProxyData[]YesArray of shared configuration items to be created or updated, with a maximum of 32 items.
configDataProxyConfigYesData proxy configuration.

Return value

TypeDescription
Promise<DataProxyResult[]>Promise used to return the result array of the batch operations.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.
15700014The parameter format is incorrect or the value range is invalid.

Example:

const newConfigData: dataShare.ProxyData[] = [{
  uri: 'datashareproxy://com.example.app1/config1',
  value: 'Value1',
  allowList: ['appIdentifier2', 'appIdentifier3'], // This string is for reference only. Replace it with the actual application identifier.
}, {
  uri: 'datashareproxy://com.example.app1/config2',
  value: 'Value2',
  allowList: ['appIdentifier3', 'appIdentifier4'], // This string is for reference only. Replace it with the actual application identifier.
}];
const config: dataShare.DataProxyConfig = {
  type: dataShare.DataProxyType.SHARED_CONFIG,
};
dataProxyHandle.publish(newConfigData, config).then((results: dataShare.DataProxyResult[]) => {
  results.forEach((result) => {
    console.info(`URI: ${result.uri}, Result: ${result.result}`);
  });
}).catch((error: BusinessError) => {
  console.error('Error publishing config:', error);
});

delete20+

delete(uris: string[], config: DataProxyConfig): Promise<DataProxyResult[]>

Deletes the specified shared configuration items based on URIs. This API uses a promise to return the result. Only the publisher is allowed to delete shared configuration items.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Parameters

NameTypeMandatoryDescription
urisstring[]YesURI array of the shared configuration items to be deleted, with a maximum of 32 URIs. The URI value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application. The value contains a maximum of 256 bytes.
configDataProxyConfigYesData proxy configuration.

Return value

TypeDescription
Promise<DataProxyResult[]>Promise used to return the result array of the batch operations.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.
15700014The parameter format is incorrect or the value range is invalid.

Example:

const urisToDelete: string[] =
  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
const config: dataShare.DataProxyConfig = {
  type: dataShare.DataProxyType.SHARED_CONFIG,
};
dataProxyHandle.delete(urisToDelete, config).then((results: dataShare.DataProxyResult[]) => {
  results.forEach((result) => {
    console.info(`URI: ${result.uri}, Result: ${result.result}`);
  });
}).catch((error: BusinessError) => {
  console.error('Error deleting config:', error);
});

get20+

get(uris: string[], config: DataProxyConfig): Promise<DataProxyGetResult[]>

Obtains a specified shared configuration item based on the URI. This API uses a promise to return the result. Only the publisher and applications in the allowed list can access the shared configuration item.

System capability: SystemCapability.DistributedDataManager.DataShare.Consumer

Parameters

NameTypeMandatoryDescription
urisstring[]YesURI array of the shared configuration items to be obtained, with a maximum of 32 URIs. The URI value is fixed at the format of "datashareproxy://{bundleName}/{path}", in which bundleName indicates the bundle name of the publisher application, and path can be set to any value but must be unique in the same application. The value contains a maximum of 256 bytes.
configDataProxyConfigYesData proxy configuration.

Return value

TypeDescription
Promise<DataProxyGetResult[]>Promise used to return the result array of the batch operations.

Error codes

For details about the error codes, see DataShare Error Codes.

IDError Message
15700000Inner error. Possible causes: The service is not ready or is being restarted abnormally.
15700014The parameter format is incorrect or the value range is invalid.

Example:

const urisToGet: string[] =
  ['datashareproxy://com.example.app1/config1', 'datashareproxy://com.example.app1/config2',];
const config: dataShare.DataProxyConfig = {
  type: dataShare.DataProxyType.SHARED_CONFIG,
};
dataProxyHandle.get(urisToGet, config).then((results: dataShare.DataProxyGetResult[]) => {
  results.forEach((result) => {
    console.info(`URI: ${result.uri}, Result: ${result.result}, AllowList: ${result.allowList}`);
  });
}).catch((error: BusinessError) => {
  console.error('Error getting config:', error);
});

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 js-apis-distributedKVStore-sys

openharmony 鸿蒙 capi-oh-preferences-h

openharmony 鸿蒙 capi-udmf-oh-udshyperlink

openharmony 鸿蒙 js-apis-data-dataSharePredicates

openharmony 鸿蒙 capi-udmf-oh-udsappitem

openharmony 鸿蒙 capi-rdb-oh-data-vbuckets

openharmony 鸿蒙 capi-rdb-oh-predicates

openharmony 鸿蒙 capi-rdb-oh-data-value

openharmony 鸿蒙 capi-preferences-oh-preferencespair

openharmony 鸿蒙 errorcode-datashare

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/yq28bo67