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
GuidesApplication FrameworkArkDataCross-Application Data SharingOne-to-Many Data SharingSharing Configurations Between Applications (ArkTS)

Sharing Configurations Between Applications (ArkTS)

When to Use

Sharing configurations between applications allows you to manage common configuration information in a centralized manner, thereby improving collaboration efficiency.

This feature is supported since API version 20.

Working Principles

The working principles of configuration sharing between applications are as follows:

  1. Configuration publisher (data provider): provides default shared configuration items and dynamically modifies them. Currently, the following configuration modes are supported:
    • Static configuration: default shared configuration items are provided when the application package is installed. The configuration takes effect immediately without depending on the application startup.
    • Dynamic configuration: configuration items can be dynamically added, deleted, or modified via related APIs, without depending on application upgrade.
  2. Configuration accessor (data consumer): calls APIs to obtain configuration information or subscribe to or unsubscribe from configuration change notifications.

Constraints

Before API version 26.0.0, an application can publish up to 32 configuration items. Starting from API version 26.0.0, the limit is increased to 64 configuration items per application. This limit applies to the combined total of static and dynamic configuration items.

Available APIs

The following APIs are provided for inter-application configuration sharing. For detailed descriptions of these APIs, see DataProxyHandle.

Public APIs

Expand
Name Description
createDataProxyHandle(): Promise<DataProxyHandle> Creates a data proxy operation handle, which is used to subscribe to, publish, and obtain configurations.

APIs for Configuration Publishers

Expand
Name Description
publish(data: ProxyData[], config: DataProxyConfig): Promise<DataProxyResult[]> Publishes or modifies configuration items.
delete(uris: string[], config: DataProxyConfig): Promise<DataProxyResult[]> Deletes the published configuration items corresponding to the specified URIs.
deleteMyPublishedData(config: DataProxyConfig): Promise<DataProxyResult[]>

Deletes all configuration items published by the publisher.

Since: 26.0.0

APIs for Configuration Accessors

Expand
Name Description
get(uris: string[], config: DataProxyConfig): Promise<DataProxyGetResult[]> Obtains configuration items.
on(event: 'dataChange', uris: string[], config: DataProxyConfig, callback: AsyncCallback<DataProxyChangeInfo[]>): DataProxyResult[] Subscribes to configuration item changes.
off(event: 'dataChange', uris: string[], config: DataProxyConfig, callback?: AsyncCallback<DataProxyChangeInfo[]>): DataProxyResult[] Unsubscribes from configuration item changes.

Configuring the Publisher

Configuration in module.json5

Reference the shared_config.json file by configuring the crossAppSharedConfig field in the module.json5 file. The shared_config.json file defines the configuration items that can be shared between applications. You should store the file in the resources/base/profile directory of the project and reference it using the $ symbol.

Collapse
Word wrap
Dark theme
Copy code
  1. {
  2. "module":{
  3. "crossAppSharedConfig": "$profile:shared_config"
  4. }
  5. }

The file name shared_config of the shared configuration file shared_config.json is customizable. The root node, crossAppSharedConfig, is an array of objects that defines the shared configuration items.

Before API version 26.0.0, an application can publish up to 32 configuration items. This limit applies to the combined total of static and dynamic configuration items. If more than 32 static configuration items are defined, only the first 32 items that comply with the crossAppSharedConfig configuration requirements are parsed. The remaining items are ignored.

Starting from API version 26.0.0, an application can publish up to 64 configuration items. This limit applies to the combined total of static and dynamic configuration items. If more than 64 static configuration items are defined, only the first 64 items that comply with the crossAppSharedConfig configuration requirements are parsed. The remaining items are ignored.

The following table describes the parameters in the crossAppSharedConfig field.

Expand
Name Description Type Mandatory
uri Unique ID of the 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 maximum length is 256 bytes. String Yes
value

Value of the shared configuration.

Before API version 26.0.0, the maximum length is 4,096 bytes.

Starting from API version 26.0.0, the maximum length is 102,400 bytes. When the value length of a shared configuration exceeds 4,096 bytes, you need to set the maxValueLength field to MAX_LENGTH_100K in the DataProxyConfig parameter of DataProxyHandle APIs to extend the length limit to 102,400 bytes. Otherwise, the API results may be unexpected.

String Yes
allowList

List of applications allowed to access the shared configuration item. The array can contain up to 256 elements. Any additional elements are ignored.

Before API version 26.0.0, each element in the array is the appIdentifier of an application, which is a numeric string with a maximum length of 128 bytes. Any appIdentifier that exceeds 128 bytes is ignored. You can use the getBundleInfoForSelf API to obtain the appIdentifier of the current application.

Starting from API version 26.0.0, the array also supports the special string "all" (case-sensitive), which allows all applications to access the shared configuration item.

String array Yes
Collapse
Word wrap
Dark theme
Copy code
  1. {
  2. "crossAppSharedConfig": [
  3. {
  4. "uri": "datashareproxy://com.example.example/key1",
  5. "value": "SHARED_CONFIG_DEMO1",
  6. "allowList": ["6917573629901742292"]
  7. },
  8. {
  9. "uri": "datashareproxy://com.example.example/key2",
  10. "value": "SHARED_CONFIG_DEMO2",
  11. "allowList": ["6917573298752100864", "6917573298752100864"]
  12. },
  13. {
  14. "uri": "datashareproxy://com.example.example/key3",
  15. "value": "ALLOW ALL APP READ",
  16. "allowList": ["all"]
  17. }
  18. ]
  19. }

Static Configuration

Static configuration refers to the default shared configuration items provided during application installation. These predefined configuration items can take effect regardless of whether the application is started.

Dynamic Configuration

You can call the publish or delete API to manage configuration items as follows:

  • Call the publish API to publish or modify configuration items.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. function publishSharedConfig() {
    2. dataShare.createDataProxyHandle().then((dataProxyHandle) => {
    3. const newConfigData: dataShare.ProxyData[] = [
    4. {
    5. uri: 'datashareproxy://com.samples.shareconfig/config1',
    6. value: 'Value1',
    7. allowList: [
    8. 'appIdentifier1',
    9. 'appIdentifier2'
    10. ]
    11. },
    12. {
    13. uri: 'datashareproxy://com.samples.shareconfig/config2',
    14. value: 'Value2',
    15. allowList: [
    16. 'appIdentifier3',
    17. 'appIdentifier4'
    18. ]
    19. }
    20. ];
    21. const config: dataShare.DataProxyConfig = {
    22. type: dataShare.DataProxyType.SHARED_CONFIG,
    23. };
    24. dataProxyHandle.publish(newConfigData, config).then((results: dataShare.DataProxyResult[]) => {
    25. results.forEach((result) => {
    26. console.info(`URI: ${result.uri}, Result: ${result.result}`);
    27. });
    28. }).catch((error: BusinessError) => {
    29. console.error('Error publishing config:', error);
    30. });
    31. }).catch((error: BusinessError) => {
    32. console.error('Error creating DataProxyHandle:', error);
    33. });
    34. }
  • Call the delete API to delete the configuration items.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. function deleteSharedConfig() {
    2. dataShare.createDataProxyHandle().then((dataProxyHandle) => {
    3. const urisToDelete: string[] = [
    4. 'datashareproxy://com.samples.shareconfig/config1',
    5. 'datashareproxy://com.samples.shareconfig/config2'
    6. ];
    7. const config: dataShare.DataProxyConfig = {
    8. type: dataShare.DataProxyType.SHARED_CONFIG,
    9. };
    10. dataProxyHandle.delete(urisToDelete, config).then((results: dataShare.DataProxyResult[]) => {
    11. results.forEach((result) => {
    12. console.info(`URI: ${result.uri}, Result: ${result.result}`);
    13. });
    14. }).catch((error: BusinessError) => {
    15. console.error('Error deleting config:', error);
    16. });
    17. }).catch((error: BusinessError) => {
    18. console.error('Error creating DataProxyHandle:', error);
    19. });
    20. }

Configuring the Accessor

You can call the get, on, or off API to perform operations as follows:

Obtaining Configuration Items

Call the get API to obtain the configuration information.

Collapse
Word wrap
Dark theme
Copy code
  1. function getSharedConfig() {
  2. dataShare.createDataProxyHandle().then((dataProxyHandle) => {
  3. const urisToGet: string[] = [
  4. 'datashareproxy://com.samples.shareconfig/config1',
  5. 'datashareproxy://com.samples.shareconfig/config2'
  6. ];
  7. const config: dataShare.DataProxyConfig = {
  8. type: dataShare.DataProxyType.SHARED_CONFIG,
  9. };
  10. dataProxyHandle.get(urisToGet, config).then((results: dataShare.DataProxyGetResult[]) => {
  11. results.forEach((result) => {
  12. console.info(`URI: ${result.uri}, Result: ${result.result}, AllowList: ${result.allowList}`);
  13. });
  14. }).catch((error: BusinessError) => {
  15. console.error('Error getting config:', error);
  16. });
  17. }).catch((error: BusinessError) => {
  18. console.error('Error creating DataProxyHandle:', error);
  19. });
  20. }

Subscribing to/Unsubscribing from Configuration Changes

Call the on API to subscribe to configuration changes or the off API to unsubscribe from the configuration changes.

Collapse
Word wrap
Dark theme
Copy code
  1. function watchConfigChanges() {
  2. dataShare.createDataProxyHandle().then((dsProxyHelper) => {
  3. const uris: string[] = [
  4. 'datashareproxy://com.samples.shareconfig/config1',
  5. 'datashareproxy://com.samples.shareconfig/config2'
  6. ];
  7. const config: dataShare.DataProxyConfig = {
  8. type: dataShare.DataProxyType.SHARED_CONFIG,
  9. };
  10. const callback = (err: BusinessError<void>, changes: dataShare.DataProxyChangeInfo[]): void => {
  11. if (err) {
  12. console.error('err:', err);
  13. } else {
  14. changes.forEach((change) => {
  15. console.info(`Change Type: ${change.type}, URI: ${change.uri}, Value: ${change.value}`);
  16. });
  17. }
  18. };
  19. // Subscribe to configuration changes.
  20. const listenResults: dataShare.DataProxyResult[] = dsProxyHelper.on('dataChange', uris, config, callback);
  21. listenResults.forEach((result) => {
  22. console.info(`URI: ${result.uri}, Result: ${result.result}`);
  23. });
  24. // Unsubscribe from configuration changes.
  25. const unListenResults: dataShare.DataProxyResult[] = dsProxyHelper.off('dataChange', uris, config, callback);
  26. unListenResults.forEach((result) => {
  27. console.info(`URI: ${result.uri}, Result: ${result.result}`);
  28. });
  29. }).catch((error: BusinessError) => {
  30. console.error('Error creating DataProxyHandle:', error);
  31. });
  32. }