• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.sendablePreferences (Shared User Preferences)
2
3
4The **sendablePreferences** module provides APIs for processing data in the form of key-value (KV) pairs, including querying, modifying, and persisting KV pairs.
5
6In the KV pairs, the key must be a string, and the value can be a number, a string, a Boolean value, a bigint, or a serializable object.
7
8The persistent files of the shared user preferences are stored in the [preferencesDir](../../application-models/application-context-stage.md#obtaining-application-file-paths) directory. Before creating a preferences object, ensure that the **preferencesDir** path can be read and written. The [encryption level](../apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) of the persistent file directory determines the access to the files. For details, see [Application File Directory and Application File Path](../../file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path).
9
10Sendable preferences can be passed between concurrent ArkTS instances (including the main thread and TaskPool or Worker threads) by reference. It allows for higher performance than [user preferences](js-apis-data-preferences.md). For more information, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).
11
12> **NOTE**
13>
14> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15>
16> The shared user preferences are not thread-safe and may cause file damage and data loss when used in multi-process scenarios. Do not use it in multi-process scenarios.
17
18## Modules to Import
19
20```ts
21import { sendablePreferences } from '@kit.ArkData';
22```
23
24## Constant
25
26**Atomic service API**: This API can be used in atomic services since API version 12.
27
28**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
29
30| Name            | Type     | Read-Only| Description                                   |
31| ---------------- | -------- | ---- | --------------------------------------- |
32| MAX_KEY_LENGTH   | number   | Yes  | Maximum length of a key, which is 1024 bytes.    |
33| MAX_VALUE_LENGTH | number   | Yes  | Maximum length of a value, which is 16 MB.|
34
35## sendablePreferences.getPreferences
36
37getPreferences(context: Context, options: Options): Promise<Preferences>
38
39Obtains a **Preferences** instance. This API uses a promise to return the result.
40
41**Atomic service API**: This API can be used in atomic services since API version 12.
42
43**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
44
45**Parameters**
46
47| Name | Type            | Mandatory| Description                                                                                                                                                                          |
48| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
49| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md)          | Yes  | Application context.|
50| options | [Options](#options) | Yes  | Configuration options of the **Preferences** instance.       |
51
52**Return value**
53
54| Type                                   | Description                              |
55| --------------------------------------- | ---------------------------------- |
56| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.<br>This instance inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).|
57
58**Error codes**
59
60For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
61
62| ID| Error Message                       |
63| -------- | ------------------------------ |
64| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
65| 801      | Capability not supported.     |
66| 15500000 | Inner error.                   |
67| 15501001 | The operations is supported in stage mode only. |
68| 15501002 | Invalid dataGroupId.     |
69
70**Example**
71
72```ts
73import { UIAbility } from '@kit.AbilityKit';
74import { BusinessError } from '@kit.BasicServicesKit';
75import { window } from '@kit.ArkUI';
76
77let preferences: sendablePreferences.Preferences;
78
79class EntryAbility extends UIAbility {
80  onWindowStageCreate(windowStage: window.WindowStage) {
81    let options: sendablePreferences.Options = { name: 'myStore' };
82    let promise = sendablePreferences.getPreferences(this.context, options);
83    promise.then((object: sendablePreferences.Preferences) => {
84      preferences = object;
85      console.info("Succeeded in getting preferences.");
86    }).catch((err: BusinessError) => {
87      console.error(`Failed to get preferences. code: ${err.code}, message: ${err.message}`);
88    });
89  }
90}
91```
92
93## sendablePreferences.getPreferencesSync
94
95getPreferencesSync(context: Context, options: Options): Preferences
96
97Obtains a **Preferences** instance. This API returns the result synchronously.
98
99**Atomic service API**: This API can be used in atomic services since API version 12.
100
101**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
102
103**Parameters**
104
105| Name | Type                 | Mandatory| Description                                                        |
106| ------- | --------------------- | ---- | ------------------------------------------------------------ |
107| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md)               | Yes  | Application context.|
108| options | [Options](#options) | Yes  | Configuration options of the **Preferences** instance.                           |
109
110**Return value**
111
112| Type                       | Description                 |
113| --------------------------- | --------------------- |
114| [Preferences](#preferences) | **Preferences** instance obtained.<br>This instance inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).|
115
116**Error codes**
117
118For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
119
120| ID| Error Message                       |
121| -------- | ------------------------------ |
122| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
123| 801      | Capability not supported.     |
124| 15500000 | Inner error.                   |
125| 15501001 | The operations is supported in stage mode only.   |
126| 15501002 | Invalid dataGroupId. |
127
128**Example**
129
130```ts
131import { UIAbility } from '@kit.AbilityKit';
132import { window } from '@kit.ArkUI';
133
134let preferences: sendablePreferences.Preferences;
135
136class EntryAbility extends UIAbility {
137  onWindowStageCreate(windowStage: window.WindowStage) {
138    let options: sendablePreferences.Options = { name: 'myStore' };
139    preferences = sendablePreferences.getPreferencesSync(this.context, options);
140  }
141}
142```
143
144## sendablePreferences.deletePreferences
145
146deletePreferences(context: Context, options: Options): Promise&lt;void&gt;
147
148Deletes a specified **Preferences** instance from the cache. If the **Preferences** instance has a corresponding persistent file, the persistent file is also deleted. This API uses a promise to return the result.
149
150Avoid using a deleted **Preferences** instance to perform data operations, which may cause data inconsistency.
151
152**Atomic service API**: This API can be used in atomic services since API version 12.
153
154**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
155
156**Parameters**
157
158| Name | Type            | Mandatory| Description                                                                        |
159| ------- | ---------------- | ---- | ----------------------------------------------------------------------------|
160| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md)          | Yes  | Application context.|
161| options | [Options](#options) | Yes  | Configuration options of the **Preferences** instance.                                                                           |
162
163**Return value**
164
165| Type               | Description                     |
166| ------------------- | ------------------------- |
167| Promise&lt;void&gt; | Promise that returns no value.|
168
169**Error codes**
170
171For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
172
173| ID| Error Message                       |
174| -------- | ------------------------------ |
175| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
176| 801      | Capability not supported.     |
177| 15500000 | Inner error.                   |
178| 15500010 | Failed to delete the user preferences persistence file. |
179| 15501001 | The operations is supported in stage mode only. |
180| 15501002 | Invalid dataGroupId. |
181
182**Example**
183
184```ts
185import { UIAbility } from '@kit.AbilityKit';
186import { BusinessError } from '@kit.BasicServicesKit';
187import { window } from '@kit.ArkUI';
188
189class EntryAbility extends UIAbility {
190  onWindowStageCreate(windowStage: window.WindowStage) {
191    let options: sendablePreferences.Options = { name: 'myStore' };
192    let promise = sendablePreferences.deletePreferences(this.context, options);
193    promise.then(() => {
194      console.info("Succeeded in deleting preferences.");
195    }).catch((err: BusinessError) => {
196      console.error(`Failed to delete preferences. code: ${err.code}, message: ${err.message}`);
197    });
198  }
199}
200```
201
202## sendablePreferences.removePreferencesFromCache
203
204removePreferencesFromCache(context: Context, options: Options): Promise&lt;void&gt;
205
206Removes a **Preferences** instance from the cache. This API uses a promise to return the result.
207
208After an application calls [getPreferences](#sendablepreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#sendablepreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a **Preferences** instance.
209
210**Atomic service API**: This API can be used in atomic services since API version 12.
211
212**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
213
214**Parameters**
215
216| Name | Type            | Mandatory| Description                                                                                                                     |
217| ------- | ---------------- | ---- | ----------------------------------------------------------------------------------------------------------------------- |
218| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md)          | Yes  | Application context.|
219| options | [Options](#options) | Yes  | Configuration options of the **Preferences** instance.                                                                                   |
220
221**Return value**
222
223| Type               | Description                     |
224| ------------------- | ------------------------- |
225| Promise&lt;void&gt; | Promise that returns no value.|
226
227**Error codes**
228
229For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
230
231| ID| Error Message                       |
232| -------- | ------------------------------ |
233| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
234| 801      | Capability not supported.     |
235| 15500000 | Inner error.                   |
236| 15501001 | The operations is supported in stage mode only. |
237| 15501002 | Invalid dataGroupId.     |
238
239**Example**
240
241```ts
242import { UIAbility } from '@kit.AbilityKit';
243import { BusinessError } from '@kit.BasicServicesKit';
244import { window } from '@kit.ArkUI';
245
246class EntryAbility extends UIAbility {
247  onWindowStageCreate(windowStage: window.WindowStage) {
248    let options: sendablePreferences.Options = { name: 'myStore' };
249    let promise = sendablePreferences.removePreferencesFromCache(this.context, options);
250    promise.then(() => {
251      console.info("Succeeded in removing preferences.");
252    }).catch((err: BusinessError) => {
253      console.error(`Failed to remove preferences. code: ${err.code}, message: ${err.message}`);
254    });
255  }
256}
257```
258
259## sendablePreferences.removePreferencesFromCacheSync
260
261removePreferencesFromCacheSync(context: Context, options: Options):void
262
263Removes a **Preferences** instance from the cache. This API returns the result synchronously.
264
265After an application calls [getPreferences](#sendablepreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#sendablepreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a **Preferences** instance.
266
267**Atomic service API**: This API can be used in atomic services since API version 12.
268
269**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
270
271**Parameters**
272
273| Name | Type                 | Mandatory| Description                                                        |
274| ------- | --------------------- | ---- | ------------------------------------------------------------ |
275| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md)               | Yes  | Application context.|
276| options | [Options](#options) | Yes  | Configuration options of the **Preferences** instance.                           |
277
278**Error codes**
279
280For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
281
282| ID| Error Message                       |
283| -------- | ------------------------------ |
284| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
285| 801      | Capability not supported.     |
286| 15500000 | Inner error.                   |
287| 15501001 | The operations is supported in stage mode only.   |
288| 15501002 | Invalid dataGroupId. |
289
290**Example**
291
292```ts
293import { UIAbility } from '@kit.AbilityKit';
294import { window } from '@kit.ArkUI';
295
296class EntryAbility extends UIAbility {
297  onWindowStageCreate(windowStage: window.WindowStage) {
298    let options: sendablePreferences.Options = { name: 'myStore' };
299    sendablePreferences.removePreferencesFromCacheSync(this.context, options);
300  }
301}
302```
303
304## Options
305
306Represents the configuration options of a **Preferences** instance.
307
308**Atomic service API**: This API can be used in atomic services since API version 12.
309
310**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
311
312| Name       | Type  | Mandatory| Description                                                        |
313| ----------- | ------ | ---- | ------------------------------------------------------------ |
314| name        | string | Yes  | Name of the **Preferences** instance.                                     |
315| dataGroupId | string\|null | No  | Application group ID. <!--RP1-->Currently, this parameter is not supported.<!--RP1End--><br>This parameter is optional. A **Preferences** instance will be created in the sandbox path corresponding to the specified **dataGroupId**. If this parameter is not specified, the **Preferences** instance is created in the sandbox directory of the application.<br> **Model restriction**: This attribute can be used only in the stage model.|
316
317
318## Preferences
319
320Provides APIs for obtaining and modifying **Preferences** instances. **Preferences** inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference.
321
322Before calling any API of **Preferences**, obtain a **Preferences** instance by using [sendablePreferences.getPreferences](#sendablepreferencesgetpreferences).
323
324### get
325
326get(key: string, defValue: lang.ISendable): Promise&lt;lang.ISendable&gt;
327
328Obtains the value of a key from this **Preferences** instance. This API uses a promise to return the result. If the value is null or is not of the default value type, **defValue** is returned.
329
330**Atomic service API**: This API can be used in atomic services since API version 12.
331
332**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
333
334 **Parameters**
335
336| Name  | Type                   | Mandatory| Description |
337| -------- | ----------------------- | ---- |--------|
338| key      | string                  | Yes  | Key of the data to obtain. It cannot be empty. |
339| defValue | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes  | Default value to be returned.|
340
341**Return value**
342
343| Type                               | Description                         |
344| ----------------------------------- | ----------------------------- |
345| Promise&lt;[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)&gt; | Promise used to return the value obtained.<br>This instance inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).|
346
347**Error codes**
348
349For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
350
351| ID| Error Message                       |
352| -------- | ------------------------------ |
353| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
354| 15500000 | Inner error.                   |
355
356**Example**
357
358```ts
359import { BusinessError } from '@kit.BasicServicesKit';
360import { lang } from '@kit.ArkTS';
361
362let promise = preferences.get('startup', 'default');
363promise.then((data: lang.ISendable) => {
364  let dataStr = data as string;
365  console.info(`Succeeded in getting value of 'startup'. Data: ${dataStr}`);
366}).catch((err: BusinessError) => {
367  console.error(`Failed to get value of 'startup'. code: ${err.code}, message: ${err.message}`);
368});
369```
370
371### getSync
372
373getSync(key: string, defValue: lang.ISendable): lang.ISendable
374
375Obtains the value of a key from this **Preferences** instance. This API returns the result synchronously. If the value is null or is not of the default value type, **defValue** is returned.
376
377**Atomic service API**: This API can be used in atomic services since API version 12.
378
379**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
380
381**Parameters**
382
383| Name  | Type                   | Mandatory| Description           |
384| -------- | ----------------------- | ---- |---------------------|
385| key      | string                  | Yes  | Key of the data to obtain. It cannot be empty. |
386| defValue | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes  | Default value to be returned.|
387
388**Return value**
389
390| Type                               | Description                         |
391| ----------------------------------- | ----------------------------- |
392| [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Value obtained.<br>This instance inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).|
393
394**Error codes**
395
396For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
397
398| ID| Error Message                       |
399| -------- | ------------------------------ |
400| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
401| 15500000 | Inner error.                   |
402
403**Example**
404
405```ts
406import { lang } from '@kit.ArkTS';
407let value: lang.ISendable = preferences.getSync('startup', 'default');
408```
409
410### getAll
411
412getAll(): Promise&lt;lang.ISendable&gt;
413
414Obtains all KV pairs from this **Preferences** instance. This API uses a promise to return the result.
415
416**Atomic service API**: This API can be used in atomic services since API version 12.
417
418**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
419
420**Return value**
421
422| Type                 | Description                                       |
423| --------------------- | ------------------------------------------- |
424| Promise&lt;[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)&gt; | Promise used to return the KV pairs obtained.<br>This object inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md). |
425
426**Error codes**
427
428For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
429
430| ID| Error Message                       |
431| -------- | ------------------------------ |
432| 15500000 | Inner error.                   |
433
434**Example**
435
436```ts
437import { BusinessError } from '@kit.BasicServicesKit';
438import { lang } from '@kit.ArkTS';
439
440let promise = preferences.getAll();
441promise.then((keyValues: lang.ISendable) => {
442  for (let value of Object.keys(keyValues)) {
443    console.info("getAll " + JSON.stringify(value));
444  }
445}).catch((err: BusinessError) => {
446  console.error(`Failed to get all key-values. code: ${err.code}, message: ${err.message}`);
447});
448```
449
450### getAllSync
451
452getAllSync(): lang.ISendable
453
454Obtains all KV pairs from this **Preferences** instance. This API returns the result synchronously.
455
456**Atomic service API**: This API can be used in atomic services since API version 12.
457
458**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
459
460**Return value**
461
462| Type                 | Description                                       |
463| --------------------- | ------------------------------------------- |
464| [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | All KV pairs obtained.<br>This object inherits from [ISendable](../../arkts-utils/arkts-sendable.md#isendable) and can be passed between concurrent ArkTS instances (including the main thread and the TaskPool or Worker threads) by reference. For details, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md).|
465
466**Error codes**
467
468For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
469
470| ID| Error Message                       |
471| -------- | ------------------------------ |
472| 15500000 | Inner error.                   |
473
474**Example**
475
476```ts
477import { lang } from '@kit.ArkTS';
478
479let keyValues: lang.ISendable = preferences.getAllSync();
480for (let value of Object.keys(keyValues)) {
481  console.info("getAll " + JSON.stringify(value));
482}
483```
484
485### put
486
487put(key: string, value: lang.ISendable): Promise&lt;void&gt;
488
489Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
490
491  > **NOTE**
492  >
493  > If the value contains a string that is not in UTF-8 format, store it in a Uint8Array. Otherwise, the persistent file may be damaged due to format errors.
494  >
495  > If the key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
496
497**Atomic service API**: This API can be used in atomic services since API version 12.
498
499**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
500
501**Parameters**
502
503| Name| Type                   | Mandatory| Description                        |
504| ------ | ----------------------- | ---- |--------------------------|
505| key    | string                  | Yes  | Key of the data. It cannot be empty. |
506| value  | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes  | Value to write.|
507
508**Return value**
509
510| Type               | Description                     |
511| ------------------- | ------------------------- |
512| Promise&lt;void&gt; | Promise that returns no value.|
513
514**Error codes**
515
516For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
517
518| ID| Error Message                       |
519| -------- | ------------------------------ |
520| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
521| 15500000 | Inner error.                   |
522
523**Example**
524
525```ts
526import { BusinessError } from '@kit.BasicServicesKit';
527
528let promise = preferences.put('startup', 'auto');
529promise.then(() => {
530  console.info("Succeeded in putting value of 'startup'.");
531}).catch((err: BusinessError) => {
532  console.error(`Failed to put value of 'startup'. code: ${err.code}, message: ${err.message}`);
533});
534```
535
536### putSync
537
538putSync(key: string, value: lang.ISendable): void
539
540Writes data to this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
541
542  > **NOTE**
543  >
544  > If the value contains a string that is not in UTF-8 format, store it in a Uint8Array. Otherwise, the persistent file may be damaged due to format errors.
545  >
546  > If the key already exists, **putSync()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
547
548**Atomic service API**: This API can be used in atomic services since API version 12.
549
550**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
551
552**Parameters**
553
554| Name| Type                   | Mandatory| Description                                                        |
555| ------ | ----------------------- | ---- | ------------------------ |
556| key    | string                  | Yes  | Key of the data. It cannot be empty.|
557| value  | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes  | Value to write.|
558
559**Error codes**
560
561For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
562
563| ID| Error Message                       |
564| -------- | ------------------------------ |
565| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
566| 15500000 | Inner error.                   |
567
568**Example**
569
570```ts
571preferences.putSync('startup', 'auto');
572```
573
574### has
575
576has(key: string): Promise&lt;boolean&gt;
577
578Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result.
579
580**Atomic service API**: This API can be used in atomic services since API version 12.
581
582**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
583
584**Parameters**
585
586| Name| Type  | Mandatory| Description                           |
587| ------ | ------ | ---- | ------------------------------- |
588| key    | string | Yes  | Key of the data to check. It cannot be empty.|
589
590**Return value**
591
592| Type                  | Description                                                        |
593| ---------------------- | ------------------------------------------------------------ |
594| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the **Preferences** instance contains the KV pair; the value **false** means the opposite.|
595
596**Error codes**
597
598For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
599
600| ID| Error Message                       |
601| -------- | ------------------------------ |
602| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
603| 15500000 | Inner error.                   |
604
605**Example**
606
607```ts
608import { BusinessError } from '@kit.BasicServicesKit';
609
610let promise = preferences.has('startup');
611promise.then((val: boolean) => {
612  if (val) {
613    console.info("The key 'startup' is contained.");
614  } else {
615    console.error("The key 'startup' does not contain.");
616  }
617}).catch((err: BusinessError) => {
618  console.error(`Failed to check the key 'startup'. code: ${err.code}, message: ${err.message}`);
619});
620```
621
622### hasSync
623
624hasSync(key: string): boolean
625
626Checks whether this **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously.
627
628**Atomic service API**: This API can be used in atomic services since API version 12.
629
630**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
631
632**Parameters**
633
634| Name| Type  | Mandatory| Description                           |
635| ------ | ------ | ---- | ------------------------------- |
636| key    | string | Yes  | Key of the data to check. It cannot be empty.|
637
638**Return value**
639
640| Type                  | Description                                                        |
641| ---------------------- | ------------------------------------------------------------ |
642| boolean | The value **true** means the **Preferences** instance contains the KV pair; the value **false** means the opposite.|
643
644**Error codes**
645
646For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
647
648| ID| Error Message                       |
649| -------- | ------------------------------ |
650| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
651| 15500000 | Inner error.                   |
652
653**Example**
654
655```ts
656let isExist: boolean = preferences.hasSync('startup');
657if (isExist) {
658  console.info("The key 'startup' is contained.");
659} else {
660  console.error("The key 'startup' does not contain.");
661}
662```
663
664### delete
665
666delete(key: string): Promise&lt;void&gt;
667
668Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
669
670**Atomic service API**: This API can be used in atomic services since API version 12.
671
672**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
673
674**Parameters**
675
676| Name| Type  | Mandatory| Description                           |
677| ------ | ------ | ---- | ------------------------------- |
678| key    | string | Yes  | Key of the KV pair to delete. It cannot be empty.|
679
680**Return value**
681
682| Type               | Description                     |
683| ------------------- | ------------------------- |
684| Promise&lt;void&gt; | Promise that returns no value.|
685
686**Error codes**
687
688For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
689
690| ID| Error Message                       |
691| -------- | ------------------------------ |
692| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
693| 15500000 | Inner error.                   |
694
695**Example**
696
697```ts
698import { BusinessError } from '@kit.BasicServicesKit';
699
700let promise = preferences.delete('startup');
701promise.then(() => {
702  console.info("Succeeded in deleting the key 'startup'.");
703}).catch((err: BusinessError) => {
704  console.error(`Failed to delete the key 'startup'. code: ${err.code}, message: ${err.message}`);
705});
706```
707
708### deleteSync
709
710deleteSync(key: string): void
711
712Deletes a KV pair from this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
713
714**Atomic service API**: This API can be used in atomic services since API version 12.
715
716**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
717
718**Parameters**
719
720| Name| Type  | Mandatory| Description                           |
721| ------ | ------ | ---- | ------------------------------- |
722| key    | string | Yes  | Key of the KV pair to delete. It cannot be empty.|
723
724**Error codes**
725
726For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
727
728| ID| Error Message                       |
729| -------- | ------------------------------ |
730| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
731| 15500000 | Inner error.                   |
732
733**Example**
734
735```ts
736preferences.deleteSync('startup');
737```
738
739### flush
740
741flush(): Promise&lt;void&gt;
742
743Flushes the data in this **Preferences** instance to the persistent file. This API uses a promise to return the result.
744
745  > **NOTE**
746  >
747  > If no data is modified or the modified data is the same as the cached data, the persistence file will not be updated.
748
749**Atomic service API**: This API can be used in atomic services since API version 12.
750
751**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
752
753**Return value**
754
755| Type               | Description                     |
756| ------------------- | ------------------------- |
757| Promise&lt;void&gt; | Promise that returns no value.|
758
759**Error codes**
760
761For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
762
763| ID| Error Message                       |
764| -------- | ------------------------------ |
765| 15500000 | Inner error.                   |
766
767**Example**
768
769```ts
770import { BusinessError } from '@kit.BasicServicesKit';
771
772let promise = preferences.flush();
773promise.then(() => {
774  console.info("Succeeded in flushing.");
775}).catch((err: BusinessError) => {
776  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
777});
778```
779
780### flushSync<sup>14+</sup>
781
782flushSync(): void
783
784Flushes the data in the cached **Preferences** instance to the persistent file.
785
786  > **NOTE**
787  >
788  > If no data is modified or the modified data is the same as the cached data, the persistence file will not be updated.
789
790**Atomic service API**: This API can be used in atomic services since API version 14.
791
792**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
793
794**Error codes**
795
796For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
797
798| ID| Error Message                       |
799| -------- | ------------------------------ |
800| 15500000 | Inner error.                   |
801
802**Example**
803
804```ts
805preferences.flushSync();
806```
807
808### clear
809
810clear(): Promise&lt;void&gt;
811
812Clears this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
813
814**Atomic service API**: This API can be used in atomic services since API version 12.
815
816**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
817
818**Return value**
819
820| Type               | Description                     |
821| ------------------- | ------------------------- |
822| Promise&lt;void&gt; | Promise that returns no value.|
823
824**Error codes**
825
826For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
827
828| ID| Error Message                       |
829| -------- | ------------------------------ |
830| 15500000 | Inner error.                   |
831
832**Example**
833
834```ts
835import { BusinessError } from '@kit.BasicServicesKit';
836
837let promise = preferences.clear();
838promise.then(() => {
839  console.info("Succeeded in clearing.");
840}).catch((err: BusinessError) => {
841  console.error(`Failed to clear. code: ${err.code}, message: ${err.message}`);
842});
843```
844
845### clearSync
846
847clearSync(): void
848
849Clears this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
850
851**Atomic service API**: This API can be used in atomic services since API version 12.
852
853**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
854
855**Error codes**
856
857For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
858
859| ID| Error Message                       |
860| -------- | ------------------------------ |
861| 15500000 | Inner error.                   |
862
863**Example**
864
865```ts
866preferences.clearSync();
867```
868
869### on('change')
870
871on(type: 'change', callback: Callback&lt;string&gt;): void
872
873Subscribes to data changes. The registered callback will be invoked to return the new value if the data change is [flushed](#flush).
874
875  > **NOTE**
876  >
877  > After [removePreferencesFromCache](#sendablepreferencesremovepreferencesfromcache) or [deletePreferences](#sendablepreferencesdeletepreferences) is called, the data change subscription will be automatically canceled. After [getPreferences](#sendablepreferencesgetpreferences) is called again, you need to subscribe to data changes again.
878
879**Atomic service API**: This API can be used in atomic services since API version 12.
880
881**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
882
883**Parameters**
884
885| Name  | Type    | Mandatory| Description                                    |
886| -------- | -------- | ---- | ---------------------------------------- |
887| type     | string   | Yes  | Event type. The value is **'change'**, which indicates data changes.|
888| callback | Callback&lt;string&gt; | Yes  | Callback used to return the key whose value is changed.    |
889
890**Error codes**
891
892For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
893
894| ID| Error Message                       |
895| -------- | ------------------------------ |
896| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
897| 15500000 | Inner error.                   |
898
899**Example**
900
901```ts
902import { BusinessError } from '@kit.BasicServicesKit';
903
904let observer = (key: string) => {
905  console.info("The key " + key + " changed.");
906};
907preferences.on('change', observer);
908preferences.putSync('startup', 'manual');
909preferences.flush().then(() => {
910  console.info("Succeeded in flushing.");
911}).catch((err: BusinessError) => {
912  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
913});
914```
915
916### on('multiProcessChange')
917
918on(type: 'multiProcessChange', callback: Callback&lt;string&gt;): void
919
920Subscribes to data changes between processes. When multiple processes hold the same preference file, calling [flush](#flush) in any process (including the current process) will trigger the callback in this API.
921
922This API is provided for applications that have applied for [dataGroupId](#options). Avoid using this API for the applications that have not applied for **dataGroupId** because calling it in multiple process may damage the persistent files and cause data loss.
923
924  > **NOTE**
925  >
926  > The maximum number of subscriptions for inter-process data change of the same persistent file for the current process is 50. Once the limit is reached, the subscription will fail. You are advised to cancel the subscription in a timely manner after the callback is triggered.
927  >
928  > After [removePreferencesFromCache](#sendablepreferencesremovepreferencesfromcache) or [deletePreferences](#sendablepreferencesdeletepreferences) is called, the data change subscription will be automatically canceled. After [getPreferences](#sendablepreferencesgetpreferences) is called again, you need to subscribe to data changes again.
929
930**Atomic service API**: This API can be used in atomic services since API version 12.
931
932**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
933
934**Parameters**
935
936| Name  | Type    | Mandatory| Description                                                        |
937| -------- | -------- | ---- | ------------------------------------------------------------ |
938| type     | string   | Yes  | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.|
939| callback | Callback&lt;string&gt; | Yes  | Callback used to return the key whose value is changed.                  |
940
941**Error codes**
942
943For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
944
945| ID| Error Message                               |
946| -------- | -------------------------------------- |
947| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
948| 15500000 | Inner error.                           |
949| 15500019 | Failed to obtain the subscription service. |
950
951**Example**
952
953```ts
954import { BusinessError } from '@kit.BasicServicesKit';
955
956let observer = (key: string) => {
957  console.info("The key " + key + " changed.");
958};
959preferences.on('multiProcessChange', observer);
960preferences.putSync('startup', 'manual');
961preferences.flush().then(() => {
962  console.info("Succeeded in flushing.");
963}).catch((err: BusinessError) => {
964  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
965});
966```
967
968### on('dataChange')
969
970on(type: 'dataChange', keys: Array&lt;string&gt;, callback: Callback&lt;lang.ISendable&gt;): void
971
972Subscribes to changes of specific data. The registered callback will be invoked only after the values of the specified keys are changed and [flushed](#flush).
973
974  > **NOTE**
975  >
976  > After [removePreferencesFromCache](#sendablepreferencesremovepreferencesfromcache) or [deletePreferences](#sendablepreferencesdeletepreferences) is called, the data change subscription will be automatically canceled. After [getPreferences](#sendablepreferencesgetpreferences) is called again, you need to subscribe to data changes again.
977
978**Atomic service API**: This API can be used in atomic services since API version 12.
979
980**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
981
982**Parameters**
983
984| Name  | Type                                                        | Mandatory| Description                                                        |
985| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
986| type     | string                                                       | Yes  | Event type. The value is **'dataChange'**, which indicates data changes.          |
987| keys     | Array&lt;string&gt;                                          | Yes  | Keys to be observed.                                         |
988| callback | callback: Callback&lt;[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)&gt; | Yes  | Callback used to return the KV pairs changed. The keys are the keys observed, and the values are the new values. The values support the following types: number, string, boolean, bigint, and serializable object.|
989
990**Error codes**
991
992For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
993
994| ID| Error Message                       |
995| -------- | ------------------------------ |
996| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
997| 15500000 | Inner error.                   |
998
999**Example**
1000
1001```ts
1002import { BusinessError } from '@kit.BasicServicesKit';
1003import { lang } from '@kit.ArkTS';
1004
1005let observer = (data: lang.ISendable) => {
1006  console.info(`observer : ${data}`);
1007};
1008let keys = ['name', 'age'];
1009preferences.on('dataChange', keys, observer);
1010preferences.putSync('name', 'xiaohong');
1011preferences.putSync('weight', 125);
1012preferences.flush().then(() => {
1013  console.info("Succeeded in flushing.");
1014}).catch((err: BusinessError) => {
1015  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
1016});
1017```
1018
1019### off('change')
1020
1021off(type: 'change', callback?: Callback&lt;string&gt;): void
1022
1023Unsubscribes from data changes.
1024
1025**Atomic service API**: This API can be used in atomic services since API version 12.
1026
1027**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1028
1029**Parameters**
1030
1031| Name  | Type    | Mandatory| Description                                                        |
1032| -------- | -------- | ---- | ------------------------------------------------------------ |
1033| type     | string   | Yes  | Event type. The value is **'change'**, which indicates data changes.                    |
1034| callback | Callback&lt;string&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.|
1035
1036**Error codes**
1037
1038For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1039
1040| ID| Error Message                       |
1041| -------- | ------------------------------ |
1042| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
1043| 15500000 | Inner error.                   |
1044
1045**Example**
1046
1047```ts
1048import { BusinessError } from '@kit.BasicServicesKit';
1049
1050let observer = (key: string) => {
1051  console.info("The key " + key + " changed.");
1052};
1053preferences.on('change', observer);
1054preferences.putSync('startup', 'auto');
1055preferences.flush().then(() => {
1056  console.info("Succeeded in flushing.");
1057  preferences.off('change', observer);
1058}).catch((err: BusinessError) => {
1059  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
1060});
1061```
1062
1063### off('multiProcessChange')
1064
1065off(type: 'multiProcessChange', callback?: Callback&lt;string&gt;): void
1066
1067Unsubscribes from inter-process data changes.
1068
1069This API is provided for applications that have applied for [dataGroupId](#options). Avoid using this API for the applications that have not applied for **dataGroupId** because calling it in multiple process may damage the persistent files and cause data loss.
1070
1071**Atomic service API**: This API can be used in atomic services since API version 12.
1072
1073**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1074
1075**Parameters**
1076
1077| Name  | Type    | Mandatory| Description                                                        |
1078| -------- | -------- | ---- | ------------------------------------------------------------ |
1079| type     | string   | Yes  | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.|
1080| callback | Callback&lt;string&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.|
1081
1082**Error codes**
1083
1084For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1085
1086| ID| Error Message                       |
1087| -------- | ------------------------------ |
1088| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
1089| 15500000 | Inner error.                   |
1090
1091**Example**
1092
1093```ts
1094import { BusinessError } from '@kit.BasicServicesKit';
1095
1096let observer = (key: string) => {
1097  console.info("The key " + key + " changed.");
1098};
1099preferences.on('multiProcessChange', observer);
1100preferences.putSync('startup', 'auto');
1101preferences.flush().then(() => {
1102  console.info("Succeeded in flushing.");
1103  preferences.off('multiProcessChange', observer);
1104}).catch((err: BusinessError) => {
1105  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
1106});
1107```
1108### off('dataChange')
1109
1110off(type: 'dataChange', keys: Array&lt;string&gt;, callback?: Callback&lt;lang.ISendable&gt;): void
1111
1112Unsubscribes from changes of specific data.
1113
1114**Atomic service API**: This API can be used in atomic services since API version 12.
1115
1116**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1117
1118**Parameters**
1119
1120| Name  | Type                                                        | Mandatory| Description                                                        |
1121| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
1122| type     | string                                                       | Yes  | Event type. The value is **'dataChange'**, which indicates data changes.          |
1123| keys     | Array&lt;string&gt;                                          | Yes  | Keys to be unsubscribed from. If this parameter is not specified, this API unsubscribes from the changes of all keys.|
1124| callback | Callback&lt;[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the changes of the specified data.|
1125
1126**Error codes**
1127
1128For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1129
1130| ID| Error Message                       |
1131| -------- | ------------------------------ |
1132| 401      | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed.                       |
1133| 15500000 | Inner error.                   |
1134
1135**Example**
1136
1137```ts
1138import { BusinessError } from '@kit.BasicServicesKit';
1139import { lang } from '@kit.ArkTS';
1140
1141let observer = (data: lang.ISendable) => {
1142  console.info(`observer : ${data}`);
1143};
1144let keys = ['name', 'age'];
1145preferences.on('dataChange', keys, observer);
1146preferences.putSync('name', 'xiaohong');
1147preferences.putSync('weight', 125);
1148preferences.flush().then(() => {
1149  console.info("Succeeded in flushing.");
1150  preferences.off('dataChange', keys, observer);
1151}).catch((err: BusinessError) => {
1152  console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`);
1153});
1154```
1155