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 default encryption level of sendable preferences is EL2, and the persistent files are stored in the corresponding **el2/** directory. If there is no lock screen password, the sendable preferences can be directly accessed after the device is powered on. If there is a lock screen password, the data can be accessed only after at least one successful unlock operation (by PIN, fingerprint, or facial authentication). For security purposes, avoid direct access to sendable preferences without the screen unlock operation. For details about how to modify the encryption level, see [Obtaining and Modifying Encryption Levels](../../../application-dev/application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). 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| Readable| Writable| Description | 31| ---------------- | -------- | ---- | ---- | --------------------------------------- | 32| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 1024 bytes. | 33| MAX_VALUE_LENGTH | number | Yes | No | Maximum value length, which is 16 x 1024 x 1024 bytes.| 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<[Preferences](#preferences)> | 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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 65| 801 | Capability not supported. | 66| 15500000 | Inner error. | 67| 15501001 | Only supported in stage mode. | 68| 15501002 | The data group id is not valid. | 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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 123| 801 | Capability not supported. | 124| 15500000 | Inner error. | 125| 15501001 | Only supported in stage mode. | 126| 15501002 | The data group id is not valid. | 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<void> 147 148Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be 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<void> | 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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 176| 801 | Capability not supported. | 177| 15500000 | Inner error. | 178| 15500010 | Failed to delete preferences file. | 179| 15501001 | Only supported in stage mode. | 180| 15501002 | The data group id is not valid. | 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<void> 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 new **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<void> | 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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 234| 801 | Capability not supported. | 235| 15500000 | Inner error. | 236| 15501001 | Only supported in stage mode. | 237| 15501002 | The data group id is not valid. | 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 new **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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 285| 801 | Capability not supported. | 286| 15500000 | Inner error. | 287| 15501001 | Only supported in stage mode. | 288| 15501002 | The data group id is not valid. | 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, which needs to be obtained from AppGallery. This parameter is not supported currently.<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<lang.ISendable> 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<[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)> | 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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>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:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>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<lang.ISendable> 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<[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)> | 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<void> 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 key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists. 494 495**Atomic service API**: This API can be used in atomic services since API version 12. 496 497**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 498 499**Parameters** 500 501| Name| Type | Mandatory| Description | 502| ------ | ----------------------- | ---- |--------------------------| 503| key | string | Yes | Key of the data. It cannot be empty. | 504| value | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes | Value to write.| 505 506**Return value** 507 508| Type | Description | 509| ------------------- | ------------------------- | 510| Promise<void> | Promise that returns no value.| 511 512**Error codes** 513 514For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 515 516| ID| Error Message | 517| -------- | ------------------------------ | 518| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 519| 15500000 | Inner error. | 520 521**Example** 522 523```ts 524import { BusinessError } from '@kit.BasicServicesKit'; 525 526let promise = preferences.put('startup', 'auto'); 527promise.then(() => { 528 console.info("Succeeded in putting value of 'startup'."); 529}).catch((err: BusinessError) => { 530 console.error(`Failed to put value of 'startup'. code: ${err.code}, message: ${err.message}`); 531}) 532``` 533 534### putSync 535 536putSync(key: string, value: lang.ISendable): void 537 538Writes data to this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 539 540 > **NOTE** 541 > 542 > If the key already exists, **putSync()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists. 543 544**Atomic service API**: This API can be used in atomic services since API version 12. 545 546**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 547 548**Parameters** 549 550| Name| Type | Mandatory| Description | 551| ------ | ----------------------- | ---- | ------------------------ | 552| key | string | Yes | Key of the data. It cannot be empty.| 553| value | [lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable) | Yes | Value to write.| 554 555**Error codes** 556 557For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 558 559| ID| Error Message | 560| -------- | ------------------------------ | 561| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 562| 15500000 | Inner error. | 563 564**Example** 565 566```ts 567preferences.putSync('startup', 'auto'); 568``` 569 570### has 571 572has(key: string): Promise<boolean> 573 574Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result. 575 576**Atomic service API**: This API can be used in atomic services since API version 12. 577 578**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 579 580**Parameters** 581 582| Name| Type | Mandatory| Description | 583| ------ | ------ | ---- | ------------------------------- | 584| key | string | Yes | Key of the data to check. It cannot be empty.| 585 586**Return value** 587 588| Type | Description | 589| ---------------------- | ------------------------------------------------------------ | 590| Promise<boolean> | Promise used to return the result. The value **true** means the **Preferences** instance contains the KV pair; the value **false** means the opposite.| 591 592**Error codes** 593 594For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 595 596| ID| Error Message | 597| -------- | ------------------------------ | 598| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 599| 15500000 | Inner error. | 600 601**Example** 602 603```ts 604import { BusinessError } from '@kit.BasicServicesKit'; 605 606let promise = preferences.has('startup'); 607promise.then((val: boolean) => { 608 if (val) { 609 console.info("The key 'startup' is contained."); 610 } else { 611 console.error("The key 'startup' dose not contain."); 612 } 613}).catch((err: BusinessError) => { 614 console.error(`Failed to check the key 'startup'. code: ${err.code}, message: ${err.message}`); 615}) 616``` 617 618### hasSync 619 620hasSync(key: string): boolean 621 622Checks whether this **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously. 623 624**Atomic service API**: This API can be used in atomic services since API version 12. 625 626**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 627 628**Parameters** 629 630| Name| Type | Mandatory| Description | 631| ------ | ------ | ---- | ------------------------------- | 632| key | string | Yes | Key of the data to check. It cannot be empty.| 633 634**Return value** 635 636| Type | Description | 637| ---------------------- | ------------------------------------------------------------ | 638| boolean | Returns **true** if the **Preferences** instance contains the KV pair; returns **false** otherwise.| 639 640**Error codes** 641 642For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 643 644| ID| Error Message | 645| -------- | ------------------------------ | 646| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 647| 15500000 | Inner error. | 648 649**Example** 650 651```ts 652let isExist: boolean = preferences.hasSync('startup'); 653if (isExist) { 654 console.info("The key 'startup' is contained."); 655} else { 656 console.error("The key 'startup' dose not contain."); 657} 658``` 659 660### delete 661 662delete(key: string): Promise<void> 663 664Deletes 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. 665 666**Atomic service API**: This API can be used in atomic services since API version 12. 667 668**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 669 670**Parameters** 671 672| Name| Type | Mandatory| Description | 673| ------ | ------ | ---- | ------------------------------- | 674| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 675 676**Return value** 677 678| Type | Description | 679| ------------------- | ------------------------- | 680| Promise<void> | Promise that returns no value.| 681 682**Error codes** 683 684For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 685 686| ID| Error Message | 687| -------- | ------------------------------ | 688| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 689| 15500000 | Inner error. | 690 691**Example** 692 693```ts 694import { BusinessError } from '@kit.BasicServicesKit'; 695 696let promise = preferences.delete('startup'); 697promise.then(() => { 698 console.info("Succeeded in deleting the key 'startup'."); 699}).catch((err: BusinessError) => { 700 console.error(`Failed to delete the key 'startup'. code: ${err.code}, message: ${err.message}`); 701}) 702``` 703 704### deleteSync 705 706deleteSync(key: string): void 707 708Deletes a KV pair from this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 709 710**Atomic service API**: This API can be used in atomic services since API version 12. 711 712**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 713 714**Parameters** 715 716| Name| Type | Mandatory| Description | 717| ------ | ------ | ---- | ------------------------------- | 718| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 719 720**Error codes** 721 722For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 723 724| ID| Error Message | 725| -------- | ------------------------------ | 726| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 727| 15500000 | Inner error. | 728 729**Example** 730 731```ts 732preferences.deleteSync('startup'); 733``` 734 735### flush 736 737flush(): Promise<void> 738 739Flushes the data in this **Preferences** instance to the persistent file. This API uses a promise to return the result. 740 741**Atomic service API**: This API can be used in atomic services since API version 12. 742 743**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 744 745**Return value** 746 747| Type | Description | 748| ------------------- | ------------------------- | 749| Promise<void> | Promise that returns no value.| 750 751**Error codes** 752 753For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 754 755| ID| Error Message | 756| -------- | ------------------------------ | 757| 15500000 | Inner error. | 758 759**Example** 760 761```ts 762import { BusinessError } from '@kit.BasicServicesKit'; 763 764let promise = preferences.flush(); 765promise.then(() => { 766 console.info("Succeeded in flushing."); 767}).catch((err: BusinessError) => { 768 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 769}) 770``` 771 772### flushSync<sup>14+</sup> 773 774flushSync(): void 775 776Flushes the data in the cached **Preferences** instance to the persistent file. 777 778**Atomic service API**: This API can be used in atomic services since API version 14. 779 780**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 781 782**Error codes** 783 784For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 785 786| ID| Error Message | 787| -------- | ------------------------------ | 788| 15500000 | Inner error. | 789 790**Example** 791 792```ts 793preferences.flushSync(); 794``` 795 796### clear 797 798clear(): Promise<void> 799 800Clears this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 801 802**Atomic service API**: This API can be used in atomic services since API version 12. 803 804**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 805 806**Return value** 807 808| Type | Description | 809| ------------------- | ------------------------- | 810| Promise<void> | Promise that returns no value.| 811 812**Error codes** 813 814For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 815 816| ID| Error Message | 817| -------- | ------------------------------ | 818| 15500000 | Inner error. | 819 820**Example** 821 822```ts 823import { BusinessError } from '@kit.BasicServicesKit'; 824 825let promise = preferences.clear(); 826promise.then(() => { 827 console.info("Succeeded in clearing."); 828}).catch((err: BusinessError) => { 829 console.error(`Failed to clear. code: ${err.code}, message: ${err.message}`); 830}) 831``` 832 833### clearSync 834 835clearSync(): void 836 837Clears this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 838 839**Atomic service API**: This API can be used in atomic services since API version 12. 840 841**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 842 843**Error codes** 844 845For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 846 847| ID| Error Message | 848| -------- | ------------------------------ | 849| 15500000 | Inner error. | 850 851**Example** 852 853```ts 854preferences.clearSync(); 855``` 856 857### on('change') 858 859on(type: 'change', callback: Callback<string>): void 860 861Subscribes to data changes. The registered callback will be invoked to return the new value if the data change is [flushed](#flush). 862 863**Atomic service API**: This API can be used in atomic services since API version 12. 864 865**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 866 867**Parameters** 868 869| Name | Type | Mandatory| Description | 870| -------- | -------- | ---- | ---------------------------------------- | 871| type | string | Yes | Event type. The value is **'change'**, which indicates data changes.| 872| callback | Callback<string> | Yes | Callback used to return the key whose value is changed. | 873 874**Error codes** 875 876For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 877 878| ID| Error Message | 879| -------- | ------------------------------ | 880| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 881| 15500000 | Inner error. | 882 883**Example** 884 885```ts 886import { BusinessError } from '@kit.BasicServicesKit'; 887 888let observer = (key: string) => { 889 console.info("The key " + key + " changed."); 890} 891preferences.on('change', observer); 892preferences.putSync('startup', 'manual'); 893preferences.flush().then(() => { 894 console.info("Succeeded in flushing."); 895}).catch((err: BusinessError) => { 896 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 897}) 898``` 899 900### on('multiProcessChange') 901 902on(type: 'multiProcessChange', callback: Callback<string>): void 903 904Subscribes to inter-process data changes. For the multiple processes holding the same preference file, if the value of the subscribed key changes in any process, the callback in this API will be invoked after [flush()](#flush) is executed. 905 906**Atomic service API**: This API can be used in atomic services since API version 12. 907 908**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 909 910**Parameters** 911 912| Name | Type | Mandatory| Description | 913| -------- | -------- | ---- | ------------------------------------------------------------ | 914| type | string | Yes | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.| 915| callback | Callback<string> | Yes | Callback used to return the key whose value is changed. | 916 917**Error codes** 918 919For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 920 921| ID| Error Message | 922| -------- | -------------------------------------- | 923| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 924| 15500000 | Inner error. | 925| 15500019 | Failed to obtain subscription service. | 926 927**Example** 928 929```ts 930import { BusinessError } from '@kit.BasicServicesKit'; 931 932let observer = (key: string) => { 933 console.info("The key " + key + " changed."); 934} 935preferences.on('multiProcessChange', observer); 936preferences.putSync('startup', 'manual'); 937preferences.flush().then(() => { 938 console.info("Succeeded in flushing."); 939}).catch((err: BusinessError) => { 940 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 941}) 942``` 943 944### on('dataChange') 945 946on(type: 'dataChange', keys: Array<string>, callback: Callback<lang.ISendable>): void 947 948Subscribes to changes of specific data. The registered callback will be invoked only after the values of the specified keys are changed and [flushed](#flush). 949 950**Atomic service API**: This API can be used in atomic services since API version 12. 951 952**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 953 954**Parameters** 955 956| Name | Type | Mandatory| Description | 957| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 958| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | 959| keys | Array<string> | Yes | Keys to be observed. | 960| callback | callback: Callback<[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)> | 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.| 961 962**Error codes** 963 964For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 965 966| ID| Error Message | 967| -------- | ------------------------------ | 968| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 969| 15500000 | Inner error. | 970 971**Example** 972 973```ts 974import { BusinessError } from '@kit.BasicServicesKit'; 975import { lang } from '@kit.ArkTS'; 976 977let observer = (data: lang.ISendable) => { 978 console.info(`observer : ${data}`) 979} 980let keys = ['name', 'age']; 981preferences.on('dataChange', keys, observer); 982preferences.putSync('name', 'xiaohong'); 983preferences.putSync('weight', 125); 984preferences.flush().then(() => { 985 console.info("Succeeded in flushing."); 986}).catch((err: BusinessError) => { 987 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 988}); 989``` 990 991### off('change') 992 993off(type: 'change', callback?: Callback<string>): void 994 995Unsubscribes from data changes. 996 997**Atomic service API**: This API can be used in atomic services since API version 12. 998 999**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1000 1001**Parameters** 1002 1003| Name | Type | Mandatory| Description | 1004| -------- | -------- | ---- | ------------------------------------------------------------ | 1005| type | string | Yes | Event type. The value is **'change'**, which indicates data changes. | 1006| callback | Callback<string> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.| 1007 1008**Error codes** 1009 1010For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1011 1012| ID| Error Message | 1013| -------- | ------------------------------ | 1014| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1015| 15500000 | Inner error. | 1016 1017**Example** 1018 1019```ts 1020import { BusinessError } from '@kit.BasicServicesKit'; 1021 1022let observer = (key: string) => { 1023 console.info("The key " + key + " changed."); 1024} 1025preferences.on('change', observer); 1026preferences.putSync('startup', 'auto'); 1027preferences.flush().then(() => { 1028 console.info("Succeeded in flushing."); 1029 preferences.off('change', observer); 1030}).catch((err: BusinessError) => { 1031 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 1032}); 1033``` 1034 1035### off('multiProcessChange') 1036 1037off(type: 'multiProcessChange', callback?: Callback<string>): void 1038 1039Unsubscribes from inter-process data changes. 1040 1041**Atomic service API**: This API can be used in atomic services since API version 12. 1042 1043**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1044 1045**Parameters** 1046 1047| Name | Type | Mandatory| Description | 1048| -------- | -------- | ---- | ------------------------------------------------------------ | 1049| type | string | Yes | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.| 1050| callback | Callback<string> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for inter-process data changes.| 1051 1052**Error codes** 1053 1054For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1055 1056| ID| Error Message | 1057| -------- | ------------------------------ | 1058| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1059| 15500000 | Inner error. | 1060 1061**Example** 1062 1063```ts 1064import { BusinessError } from '@kit.BasicServicesKit'; 1065 1066let observer = (key: string) => { 1067 console.info("The key " + key + " changed."); 1068} 1069preferences.on('multiProcessChange', observer); 1070preferences.putSync('startup', 'auto'); 1071preferences.flush().then(() => { 1072 console.info("Succeeded in flushing."); 1073 preferences.off('multiProcessChange', observer); 1074}).catch((err: BusinessError) => { 1075 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 1076}); 1077``` 1078### off('dataChange') 1079 1080off(type: 'dataChange', keys: Array<string>, callback?: Callback<lang.ISendable>): void 1081 1082Unsubscribes from changes of specific data. 1083 1084**Atomic service API**: This API can be used in atomic services since API version 12. 1085 1086**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1087 1088**Parameters** 1089 1090| Name | Type | Mandatory| Description | 1091| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1092| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | 1093| keys | Array<string> | Yes | Keys to be unsubscribed from. If this parameter is not specified, this API unsubscribes from the changes of all keys.| 1094| callback | Callback<[lang.ISendable](../../arkts-utils/arkts-sendable.md#isendable)> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the changes of the specified data.| 1095 1096**Error codes** 1097 1098For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1099 1100| ID| Error Message | 1101| -------- | ------------------------------ | 1102| 401 | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1103| 15500000 | Inner error. | 1104 1105**Example** 1106 1107```ts 1108import { BusinessError } from '@kit.BasicServicesKit'; 1109import { lang } from '@kit.ArkTS'; 1110 1111let observer = (data: lang.ISendable) => { 1112 console.info(`observer : ${data}`) 1113} 1114let keys = ['name', 'age']; 1115preferences.on('dataChange', keys, observer); 1116preferences.putSync('name', 'xiaohong'); 1117preferences.putSync('weight', 125); 1118preferences.flush().then(() => { 1119 console.info("Succeeded in flushing."); 1120 preferences.off('dataChange', keys, observer); 1121}).catch((err: BusinessError) => { 1122 console.error(`Failed to flush. code: ${err.code}, message: ${err.message}`); 1123}); 1124``` 1125<!--no_check-->