1# @ohos.data.preferences (用户首选项) 2 3用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。 4 5数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。 6 7 8> **说明:** 9> 10> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 11 12 13## 导入模块 14 15```ts 16import dataPreferences from '@ohos.data.preferences'; 17``` 18 19## 常量 20 21**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 22 23| 名称 | 参数类型 | 可读 | 可写 | 说明 | 24| ---------------- | -------- | ---- | ---- | --------------------------------------- | 25| MAX_KEY_LENGTH | number | 是 | 否 | Key的最大长度限制为80个字节。 | 26| MAX_VALUE_LENGTH | number | 是 | 否 | Value的最大长度限制为8192个字节。 | 27 28 29## dataPreferences.getPreferences 30 31getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void 32 33获取Preferences实例,使用callback异步回调。 34 35**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 36 37**参数:** 38 39| 参数名 | 类型 | 必填 | 说明 | 40| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | 41| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 42| name | string | 是 | Preferences实例的名称。 | 43| callback | AsyncCallback<[Preferences](#preferences)> | 是 | 回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。 | 44 45**示例:** 46 47FA模型示例: 48 49```ts 50// 获取context 51import featureAbility from '@ohos.ability.featureAbility'; 52import { BusinessError } from '@ohos.base'; 53 54let context = featureAbility.getContext(); 55let preferences: dataPreferences.Preferences | null = null; 56 57try { 58 dataPreferences.getPreferences(context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => { 59 if (err) { 60 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 61 return; 62 } 63 preferences = val; 64 console.info("Succeeded in getting preferences."); 65 }) 66} catch (err) { 67 let code = (err as BusinessError).code; 68 let message = (err as BusinessError).message; 69 console.error("Failed to get preferences. code =" + code + ", message =" + message); 70} 71``` 72 73Stage模型示例: 74 75```ts 76import UIAbility from '@ohos.app.ability.UIAbility'; 77import { BusinessError } from '@ohos.base'; 78import window from '@ohos.window'; 79 80let preferences: dataPreferences.Preferences | null = null; 81 82class EntryAbility extends UIAbility { 83 onWindowStageCreate(windowStage: window.WindowStage) { 84 try { 85 dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => { 86 if (err) { 87 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 88 return; 89 } 90 preferences = val; 91 console.info("Succeeded in getting preferences."); 92 }) 93 } catch (err) { 94 let code = (err as BusinessError).code; 95 let message = (err as BusinessError).message; 96 console.error("Failed to get preferences. code =" + code + ", message =" + message); 97 } 98 } 99} 100``` 101 102## dataPreferences.getPreferences 103 104getPreferences(context: Context, name: string): Promise<Preferences> 105 106获取Preferences实例,使用Promise异步回调。 107 108**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 109 110**参数:** 111 112| 参数名 | 类型 | 必填 | 说明 | 113| ------- | ------------------------------------- | ---- | ----------------------- | 114| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 115| name | string | 是 | Preferences实例的名称。 | 116 117**返回值:** 118 119| 类型 | 说明 | 120| ------------------------------------------ | ---------------------------------- | 121| Promise<[Preferences](#preferences)> | Promise对象,返回Preferences实例。 | 122 123**示例:** 124 125FA模型示例: 126 127```ts 128// 获取context 129import featureAbility from '@ohos.ability.featureAbility'; 130import { BusinessError } from '@ohos.base' 131 132let context = featureAbility.getContext(); 133 134let preferences: dataPreferences.Preferences | null = null; 135try { 136 let promise = dataPreferences.getPreferences(context, 'myStore'); 137 promise.then((object: dataPreferences.Preferences) => { 138 preferences = object; 139 console.info("Succeeded in getting preferences."); 140 }).catch((err: BusinessError) => { 141 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 142 }) 143} catch (err) { 144 let code = (err as BusinessError).code; 145 let message = (err as BusinessError).message; 146 console.error("Failed to get preferences. code =" + code + ", message =" + message); 147} 148``` 149 150Stage模型示例: 151 152```ts 153import UIAbility from '@ohos.app.ability.UIAbility'; 154import { BusinessError } from '@ohos.base' 155import window from '@ohos.window'; 156 157let preferences: dataPreferences.Preferences | null = null; 158 159class EntryAbility extends UIAbility { 160 onWindowStageCreate(windowStage: window.WindowStage) { 161 try { 162 let promise = dataPreferences.getPreferences(this.context, 'myStore'); 163 promise.then((object: dataPreferences.Preferences) => { 164 preferences = object; 165 console.info("Succeeded in getting preferences."); 166 }).catch((err: BusinessError) => { 167 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 168 }) 169 } catch (err) { 170 let code = (err as BusinessError).code; 171 let message = (err as BusinessError).message; 172 console.error("Failed to get preferences. code =" + code + ", message =" + message); 173 } 174 } 175} 176``` 177 178## dataPreferences.getPreferences<sup>10+</sup> 179 180getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void 181 182获取Preferences实例,使用callback异步回调。 183 184**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 185 186**参数:** 187 188| 参数名 | 类型 | 必填 | 说明 | 189| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 190| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 191| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 192| callback | AsyncCallback<[Preferences](#preferences)> | 是 | 回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。 | 193 194**错误码:** 195 196以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 197 198| 错误码ID | 错误信息 | 199| -------- | ------------------------------ | 200| 15501001 | Only supported in stage mode. | 201| 15501002 | The data group id is not valid. | 202 203**示例:** 204 205FA模型示例: 206 207```ts 208// 获取context 209import featureAbility from '@ohos.ability.featureAbility'; 210import { BusinessError } from '@ohos.base' 211 212let context = featureAbility.getContext(); 213let preferences: dataPreferences.Preferences | null = null; 214 215try { 216 let options: dataPreferences.Options = { name: 'myStore' }; 217 dataPreferences.getPreferences(context, options, (err: BusinessError, val: dataPreferences.Preferences) => { 218 if (err) { 219 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 220 return; 221 } 222 preferences = val; 223 console.info("Succeeded in getting preferences."); 224 }) 225} catch (err) { 226 let code = (err as BusinessError).code; 227 let message = (err as BusinessError).message; 228 console.error("Failed to get preferences. code =" + code + ", message =" + message); 229} 230``` 231 232 233Stage模型示例: 234 235```ts 236import UIAbility from '@ohos.app.ability.UIAbility'; 237import { BusinessError } from '@ohos.base' 238import window from '@ohos.window'; 239 240let preferences: dataPreferences.Preferences | null = null; 241 242class EntryAbility extends UIAbility { 243 onWindowStageCreate(windowStage: window.WindowStage) { 244 try { 245 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 246 dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => { 247 if (err) { 248 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 249 return; 250 } 251 preferences = val; 252 console.info("Succeeded in getting preferences."); 253 }) 254 } catch (err) { 255 let code = (err as BusinessError).code; 256 let message = (err as BusinessError).message; 257 console.error("Failed to get preferences. code =" + code + ", message =" + message); 258 } 259 } 260} 261``` 262 263## dataPreferences.getPreferences<sup>10+</sup> 264 265getPreferences(context: Context, options: Options): Promise<Preferences> 266 267获取Preferences实例,使用Promise异步回调。 268 269**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 270 271**参数:** 272 273| 参数名 | 类型 | 必填 | 说明 | 274| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 275| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 276| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 277 278**返回值:** 279 280| 类型 | 说明 | 281| --------------------------------------- | ---------------------------------- | 282| Promise<[Preferences](#preferences)> | Promise对象,返回Preferences实例。 | 283 284**错误码:** 285 286以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 287 288| 错误码ID | 错误信息 | 289| -------- | ------------------------------ | 290| 15501001 | Only supported in stage mode. | 291| 15501002 | The data group id is not valid. | 292 293**示例:** 294 295FA模型示例: 296 297```ts 298// 获取context 299import featureAbility from '@ohos.ability.featureAbility'; 300import { BusinessError } from '@ohos.base' 301let context = featureAbility.getContext(); 302 303let preferences: dataPreferences.Preferences | null = null; 304try { 305 let options: dataPreferences.Options = { name: 'myStore' }; 306 let promise = dataPreferences.getPreferences(context, options); 307 promise.then((object: dataPreferences.Preferences) => { 308 preferences = object; 309 console.info("Succeeded in getting preferences."); 310 }).catch((err: BusinessError) => { 311 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 312 }) 313} catch (err) { 314 let code = (err as BusinessError).code; 315 let message = (err as BusinessError).message; 316 console.error("Failed to get preferences. code =" + code + ", message =" + message); 317} 318``` 319 320Stage模型示例: 321 322```ts 323import UIAbility from '@ohos.app.ability.UIAbility'; 324import { BusinessError } from '@ohos.base' 325import window from '@ohos.window'; 326 327let preferences: dataPreferences.Preferences | null = null; 328 329class EntryAbility extends UIAbility { 330 onWindowStageCreate(windowStage: window.WindowStage) { 331 try { 332 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 333 let promise = dataPreferences.getPreferences(this.context, options); 334 promise.then((object: dataPreferences.Preferences) => { 335 preferences = object; 336 console.info("Succeeded in getting preferences."); 337 }).catch((err: BusinessError) => { 338 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 339 }) 340 } catch (err) { 341 let code = (err as BusinessError).code; 342 let message = (err as BusinessError).message; 343 console.error("Failed to get preferences. code =" + code + ", message =" + message); 344 } 345 } 346} 347``` 348 349## dataPreferences.getPreferencesSync<sup>10+</sup> 350 351getPreferencesSync(context: Context, options: Options): Preferences 352 353获取Preferences实例,此为同步接口。 354 355**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 356 357**参数:** 358 359| 参数名 | 类型 | 必填 | 说明 | 360| ------- | --------------------- | ---- | ------------------------------------------------------------ | 361| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 362| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 363 364**返回值:** 365 366| 类型 | 说明 | 367| --------------------------- | --------------------- | 368| [Preferences](#preferences) | 返回Preferences实例。 | 369 370**错误码:** 371 372以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 373 374| 错误码ID | 错误信息 | 375| -------- | ------------------------------- | 376| 15501001 | Only supported in stage mode. | 377| 15501002 | The data group id is not valid. | 378 379**示例:** 380 381FA模型示例: 382 383```ts 384// 获取context 385import featureAbility from '@ohos.ability.featureAbility'; 386import { BusinessError } from '@ohos.base' 387 388let context = featureAbility.getContext(); 389let preferences: dataPreferences.Preferences | null = null; 390 391try { 392 let options: dataPreferences.Options = { name: 'myStore' }; 393 preferences = dataPreferences.getPreferencesSync(context, options); 394} catch (err) { 395 let code = (err as BusinessError).code; 396 let message = (err as BusinessError).message; 397 console.error("Failed to get preferences. code =" + code + ", message =" + message); 398} 399``` 400 401Stage模型示例: 402 403```ts 404import UIAbility from '@ohos.app.ability.UIAbility'; 405import { BusinessError } from '@ohos.base' 406import window from '@ohos.window'; 407 408let preferences: dataPreferences.Preferences | null = null; 409 410class EntryAbility extends UIAbility { 411 onWindowStageCreate(windowStage: window.WindowStage) { 412 try { 413 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 414 preferences = dataPreferences.getPreferencesSync(this.context, options); 415 } catch (err) { 416 let code = (err as BusinessError).code; 417 let message = (err as BusinessError).message; 418 console.error("Failed to get preferences. code =" + code + ", message =" + message); 419 } 420 } 421} 422``` 423 424## dataPreferences.deletePreferences 425 426deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void 427 428从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。 429 430调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 431 432**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 433 434**参数:** 435 436| 参数名 | 类型 | 必填 | 说明 | 437| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | 438| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 439| name | string | 是 | Preferences实例的名称。 | 440| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | 441 442**错误码:** 443 444以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 445 446| 错误码ID | 错误信息 | 447| -------- | ------------------------------| 448| 15500010 | Failed to delete preferences file. | 449 450**示例:** 451 452FA模型示例: 453 454```ts 455// 获取context 456import featureAbility from '@ohos.ability.featureAbility'; 457import { BusinessError } from '@ohos.base' 458 459let context = featureAbility.getContext(); 460 461try { 462 dataPreferences.deletePreferences(context, 'myStore', (err: BusinessError) => { 463 if (err) { 464 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 465 return; 466 } 467 console.info("Succeeded in deleting preferences." ); 468 }) 469} catch (err) { 470 let code = (err as BusinessError).code; 471 let message = (err as BusinessError).message; 472 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 473} 474``` 475 476Stage模型示例: 477 478```ts 479import UIAbility from '@ohos.app.ability.UIAbility'; 480import { BusinessError } from '@ohos.base' 481import window from '@ohos.window'; 482 483class EntryAbility extends UIAbility { 484 onWindowStageCreate(windowStage: window.WindowStage) { 485 try { 486 dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { 487 if (err) { 488 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 489 return; 490 } 491 console.info("Succeeded in deleting preferences." ); 492 }) 493 } catch (err) { 494 let code = (err as BusinessError).code; 495 let message = (err as BusinessError).message; 496 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 497 } 498 } 499} 500``` 501 502## dataPreferences.deletePreferences 503 504deletePreferences(context: Context, name: string): Promise<void> 505 506从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 507 508调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 509 510**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 511 512**参数:** 513 514| 参数名 | 类型 | 必填 | 说明 | 515| ------- | ------------------------------------- | ---- | ----------------------- | 516| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 517| name | string | 是 | Preferences实例的名称。 | 518 519**返回值:** 520 521| 类型 | 说明 | 522| ------------------- | ------------------------- | 523| Promise<void> | 无返回结果的Promise对象。 | 524 525**错误码:** 526 527以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 528 529| 错误码ID | 错误信息 | 530| -------- | ------------------------------| 531| 15500010 | Failed to delete preferences file. | 532 533**示例:** 534 535FA模型示例: 536 537```ts 538// 获取context 539import featureAbility from '@ohos.ability.featureAbility'; 540import { BusinessError } from '@ohos.base' 541 542let context = featureAbility.getContext(); 543 544try { 545 let promise = dataPreferences.deletePreferences(context, 'myStore'); 546 promise.then(() => { 547 console.info("Succeeded in deleting preferences."); 548 }).catch((err: BusinessError) => { 549 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 550 }) 551} catch (err) { 552 let code = (err as BusinessError).code; 553 let message = (err as BusinessError).message; 554 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 555} 556``` 557 558Stage模型示例: 559 560```ts 561import UIAbility from '@ohos.app.ability.UIAbility'; 562import { BusinessError } from '@ohos.base' 563import window from '@ohos.window'; 564 565class EntryAbility extends UIAbility { 566 onWindowStageCreate(windowStage: window.WindowStage) { 567 try{ 568 let promise = dataPreferences.deletePreferences(this.context, 'myStore'); 569 promise.then(() => { 570 console.info("Succeeded in deleting preferences."); 571 }).catch((err: BusinessError) => { 572 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 573 }) 574 } catch (err) { 575 let code = (err as BusinessError).code; 576 let message = (err as BusinessError).message; 577 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 578 } 579 } 580} 581``` 582 583## dataPreferences.deletePreferences<sup>10+</sup> 584 585deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void 586 587从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。 588 589调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 590 591**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 592 593**参数:** 594 595| 参数名 | 类型 | 必填 | 说明 | 596| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 597| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 598| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 599| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | 600 601**错误码:** 602 603以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 604 605| 错误码ID | 错误信息 | 606| -------- | ---------------------------------- | 607| 15500010 | Failed to delete preferences file. | 608| 15501001 | Only supported in stage mode. | 609| 15501002 | The data group id is not valid. | 610 611**示例:** 612 613FA模型示例: 614 615```ts 616// 获取context 617import featureAbility from '@ohos.ability.featureAbility'; 618import { BusinessError } from '@ohos.base' 619 620let context = featureAbility.getContext(); 621 622try { 623 let options: dataPreferences.Options = { name: 'myStore' }; 624 dataPreferences.deletePreferences(context, options, (err: BusinessError) => { 625 if (err) { 626 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 627 return; 628 } 629 console.info("Succeeded in deleting preferences." ); 630 }) 631} catch (err) { 632 let code = (err as BusinessError).code; 633 let message = (err as BusinessError).message; 634 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 635} 636``` 637 638Stage模型示例: 639 640```ts 641import UIAbility from '@ohos.app.ability.UIAbility'; 642import { BusinessError } from '@ohos.base' 643import window from '@ohos.window'; 644 645class EntryAbility extends UIAbility { 646 onWindowStageCreate(windowStage: window.WindowStage) { 647 try { 648 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 649 dataPreferences.deletePreferences(this.context, options, (err: BusinessError) => { 650 if (err) { 651 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 652 return; 653 } 654 console.info("Succeeded in deleting preferences." ); 655 }) 656 } catch (err) { 657 let code = (err as BusinessError).code; 658 let message = (err as BusinessError).message; 659 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 660 } 661 } 662} 663``` 664 665 666## dataPreferences.deletePreferences<sup>10+</sup> 667 668deletePreferences(context: Context, options: Options): Promise<void> 669 670从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 671 672调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 673 674**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 675 676**参数:** 677 678| 参数名 | 类型 | 必填 | 说明 | 679| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 680| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 681| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 682 683**返回值:** 684 685| 类型 | 说明 | 686| ------------------- | ------------------------- | 687| Promise<void> | 无返回结果的Promise对象。 | 688 689**错误码:** 690 691以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 692 693| 错误码ID | 错误信息 | 694| -------- | ---------------------------------- | 695| 15500010 | Failed to delete preferences file. | 696| 15501001 | Only supported in stage mode. | 697| 15501002 | The data group id is not valid. | 698 699**示例:** 700 701FA模型示例: 702 703```ts 704// 获取context 705import featureAbility from '@ohos.ability.featureAbility'; 706import { BusinessError } from '@ohos.base' 707 708let context = featureAbility.getContext(); 709 710try { 711 let options: dataPreferences.Options = { name: 'myStore' }; 712 let promise = dataPreferences.deletePreferences(context, options); 713 promise.then(() => { 714 console.info("Succeeded in deleting preferences."); 715 }).catch((err: BusinessError) => { 716 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 717 }) 718} catch (err) { 719 let code = (err as BusinessError).code; 720 let message = (err as BusinessError).message; 721 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 722} 723``` 724 725Stage模型示例: 726 727```ts 728import UIAbility from '@ohos.app.ability.UIAbility'; 729import { BusinessError } from '@ohos.base' 730import window from '@ohos.window'; 731 732class EntryAbility extends UIAbility { 733 onWindowStageCreate(windowStage: window.WindowStage) { 734 try{ 735 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 736 let promise = dataPreferences.deletePreferences(this.context, options); 737 promise.then(() => { 738 console.info("Succeeded in deleting preferences."); 739 }).catch((err: BusinessError) => { 740 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 741 }) 742 } catch (err) { 743 let code = (err as BusinessError).code; 744 let message = (err as BusinessError).message; 745 console.error("Failed to delete preferences. code =" + code + ", message =" + message); 746 } 747 } 748} 749``` 750 751 752## dataPreferences.removePreferencesFromCache 753 754removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void 755 756从缓存中移出指定的Preferences实例,使用callback异步回调。 757 758应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 759 760调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 761 762**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 763 764**参数:** 765 766| 参数名 | 类型 | 必填 | 说明 | 767| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | 768| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 769| name | string | 是 | Preferences实例的名称。 | 770| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | 771 772**示例:** 773 774FA模型示例: 775 776```ts 777// 获取context 778import featureAbility from '@ohos.ability.featureAbility'; 779import { BusinessError } from '@ohos.base' 780 781let context = featureAbility.getContext(); 782try { 783 dataPreferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => { 784 if (err) { 785 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 786 return; 787 } 788 console.info("Succeeded in removing preferences."); 789 }) 790} catch (err) { 791 let code = (err as BusinessError).code; 792 let message = (err as BusinessError).message; 793 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 794} 795``` 796 797Stage模型示例: 798 799```ts 800import UIAbility from '@ohos.app.ability.UIAbility'; 801import { BusinessError } from '@ohos.base' 802import window from '@ohos.window'; 803 804class EntryAbility extends UIAbility { 805 onWindowStageCreate(windowStage: window.WindowStage) { 806 try { 807 dataPreferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { 808 if (err) { 809 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 810 return; 811 } 812 console.info("Succeeded in removing preferences."); 813 }) 814 } catch (err) { 815 let code = (err as BusinessError).code; 816 let message = (err as BusinessError).message; 817 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 818 } 819 } 820} 821``` 822 823## dataPreferences.removePreferencesFromCache 824 825removePreferencesFromCache(context: Context, name: string): Promise<void> 826 827从缓存中移出指定的Preferences实例,使用Promise异步回调。 828 829应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 830 831调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 832 833**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 834 835**参数:** 836 837| 参数名 | 类型 | 必填 | 说明 | 838| ------- | ------------------------------------- | ---- | ----------------------- | 839| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 840| name | string | 是 | Preferences实例的名称。 | 841 842**返回值:** 843 844| 类型 | 说明 | 845| ------------------- | ------------------------- | 846| Promise<void> | 无返回结果的Promise对象。 | 847 848**示例:** 849 850FA模型示例: 851 852```ts 853// 获取context 854import featureAbility from '@ohos.ability.featureAbility'; 855import { BusinessError } from '@ohos.base' 856 857let context = featureAbility.getContext(); 858try { 859 let promise = dataPreferences.removePreferencesFromCache(context, 'myStore'); 860 promise.then(() => { 861 console.info("Succeeded in removing preferences."); 862 }).catch((err: BusinessError) => { 863 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 864 }) 865} catch (err) { 866 let code = (err as BusinessError).code; 867 let message = (err as BusinessError).message; 868 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 869} 870``` 871 872Stage模型示例: 873 874```ts 875import UIAbility from '@ohos.app.ability.UIAbility'; 876import { BusinessError } from '@ohos.base' 877import window from '@ohos.window'; 878 879class EntryAbility extends UIAbility { 880 onWindowStageCreate(windowStage: window.WindowStage) { 881 try { 882 let promise = dataPreferences.removePreferencesFromCache(this.context, 'myStore'); 883 promise.then(() => { 884 console.info("Succeeded in removing preferences."); 885 }).catch((err: BusinessError) => { 886 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 887 }) 888 } catch (err) { 889 let code = (err as BusinessError).code; 890 let message = (err as BusinessError).message; 891 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 892 } 893 } 894} 895``` 896 897## dataPreferences.removePreferencesFromCacheSync<sup>10+</sup> 898 899removePreferencesFromCacheSync(context: Context, name: string): void 900 901从缓存中移出指定的Preferences实例,此为同步接口。 902 903应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 904 905调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 906 907**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 908 909**参数:** 910 911| 参数名 | 类型 | 必填 | 说明 | 912| ------- | ------------------------------------- | ---- | ----------------------- | 913| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 914| name | string | 是 | Preferences实例的名称。 | 915 916**示例:** 917 918FA模型示例: 919 920```ts 921// 获取context 922import featureAbility from '@ohos.ability.featureAbility'; 923import { BusinessError } from '@ohos.base' 924let context = featureAbility.getContext(); 925try { 926 dataPreferences.removePreferencesFromCacheSync(context, 'myStore'); 927} catch (err) { 928 let code = (err as BusinessError).code; 929 let message = (err as BusinessError).message; 930 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 931} 932``` 933 934Stage模型示例: 935 936```ts 937import UIAbility from '@ohos.app.ability.UIAbility'; 938import { BusinessError } from '@ohos.base' 939import window from '@ohos.window'; 940 941class EntryAbility extends UIAbility { 942 onWindowStageCreate(windowStage: window.WindowStage) { 943 try { 944 dataPreferences.removePreferencesFromCacheSync(this.context, 'myStore'); 945 } catch (err) { 946 let code = (err as BusinessError).code; 947 let message = (err as BusinessError).message; 948 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 949 } 950 } 951} 952``` 953 954## dataPreferences.removePreferencesFromCache<sup>10+</sup> 955 956removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void 957 958从缓存中移出指定的Preferences实例,使用callback异步回调。 959 960应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 961 962调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 963 964**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 965 966**参数:** 967 968| 参数名 | 类型 | 必填 | 说明 | 969| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 970| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 971| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 972| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | 973 974**错误码:** 975 976以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 977 978| 错误码ID | 错误信息 | 979| -------- | ------------------------------ | 980| 15501001 | Only supported in stage mode. | 981| 15501002 | The data group id is not valid. | 982 983**示例:** 984 985FA模型示例: 986 987```ts 988// 获取context 989import featureAbility from '@ohos.ability.featureAbility'; 990import { BusinessError } from '@ohos.base' 991let context = featureAbility.getContext(); 992try { 993 let options: dataPreferences.Options = { name: 'myStore' }; 994 dataPreferences.removePreferencesFromCache(context, options, (err: BusinessError) => { 995 if (err) { 996 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 997 return; 998 } 999 console.info("Succeeded in removing preferences."); 1000 }) 1001} catch (err) { 1002 let code = (err as BusinessError).code; 1003 let message = (err as BusinessError).message; 1004 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1005} 1006``` 1007 1008Stage模型示例: 1009 1010```ts 1011import UIAbility from '@ohos.app.ability.UIAbility'; 1012import { BusinessError } from '@ohos.base' 1013import window from '@ohos.window'; 1014 1015class EntryAbility extends UIAbility { 1016 onWindowStageCreate(windowStage: window.WindowStage) { 1017 try { 1018 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1019 dataPreferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { 1020 if (err) { 1021 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 1022 return; 1023 } 1024 console.info("Succeeded in removing preferences."); 1025 }) 1026 } catch (err) { 1027 let code = (err as BusinessError).code; 1028 let message = (err as BusinessError).message; 1029 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1030 } 1031 } 1032} 1033``` 1034 1035## dataPreferences.removePreferencesFromCache<sup>10+</sup> 1036 1037removePreferencesFromCache(context: Context, options: Options): Promise<void> 1038 1039从缓存中移出指定的Preferences实例,使用Promise异步回调。 1040 1041应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 1042 1043调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 1044 1045**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1046 1047**参数:** 1048 1049| 参数名 | 类型 | 必填 | 说明 | 1050| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 1051| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 1052| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 1053 1054**返回值:** 1055 1056| 类型 | 说明 | 1057| ------------------- | ------------------------- | 1058| Promise<void> | 无返回结果的Promise对象。 | 1059 1060**错误码:** 1061 1062以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 1063 1064| 错误码ID | 错误信息 | 1065| -------- | ------------------------------ | 1066| 15501001 | Only supported in stage mode. | 1067| 15501002 | The data group id is not valid. | 1068 1069**示例:** 1070 1071FA模型示例: 1072 1073```ts 1074// 获取context 1075import featureAbility from '@ohos.ability.featureAbility'; 1076import { BusinessError } from '@ohos.base' 1077let context = featureAbility.getContext(); 1078try { 1079 let options: dataPreferences.Options = { name: 'myStore' }; 1080 let promise = dataPreferences.removePreferencesFromCache(context, options); 1081 promise.then(() => { 1082 console.info("Succeeded in removing preferences."); 1083 }).catch((err: BusinessError) => { 1084 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 1085 }) 1086} catch (err) { 1087 let code = (err as BusinessError).code; 1088 let message = (err as BusinessError).message; 1089 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1090} 1091``` 1092 1093Stage模型示例: 1094 1095```ts 1096import UIAbility from '@ohos.app.ability.UIAbility'; 1097import { BusinessError } from '@ohos.base' 1098import window from '@ohos.window'; 1099 1100class EntryAbility extends UIAbility { 1101 onWindowStageCreate(windowStage: window.WindowStage) { 1102 try { 1103 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1104 let promise = dataPreferences.removePreferencesFromCache(this.context, options); 1105 promise.then(() => { 1106 console.info("Succeeded in removing preferences."); 1107 }).catch((err: BusinessError) => { 1108 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 1109 }) 1110 } catch (err) { 1111 let code = (err as BusinessError).code; 1112 let message = (err as BusinessError).message; 1113 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1114 } 1115 } 1116} 1117``` 1118 1119## dataPreferences.removePreferencesFromCacheSync<sup>10+</sup> 1120 1121removePreferencesFromCacheSync(context: Context, options: Options):void 1122 1123从缓存中移出指定的Preferences实例,此为同步接口。 1124 1125应用首次调用[getPreferences](#datapreferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#datapreferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 1126 1127调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 1128 1129**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1130 1131**参数:** 1132 1133| 参数名 | 类型 | 必填 | 说明 | 1134| ------- | --------------------- | ---- | ------------------------------------------------------------ | 1135| context | Context | 是 | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | 1136| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | 1137 1138**错误码:** 1139 1140以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 1141 1142| 错误码ID | 错误信息 | 1143| -------- | ------------------------------- | 1144| 15501001 | Only supported in stage mode. | 1145| 15501002 | The data group id is not valid. | 1146 1147**示例:** 1148 1149FA模型示例: 1150 1151```ts 1152// 获取context 1153import featureAbility from '@ohos.ability.featureAbility'; 1154let context = featureAbility.getContext(); 1155try { 1156 let options: dataPreferences.Options = { name: 'myStore' }; 1157 dataPreferences.removePreferencesFromCacheSync(context, options); 1158} catch (err) { 1159 let code = (err as BusinessError).code; 1160 let message = (err as BusinessError).message; 1161 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1162} 1163``` 1164 1165Stage模型示例: 1166 1167```ts 1168import UIAbility from '@ohos.app.ability.UIAbility'; 1169import window from '@ohos.window'; 1170 1171class EntryAbility extends UIAbility { 1172 onWindowStageCreate(windowStage: window.WindowStage) { 1173 try { 1174 let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1175 dataPreferences.removePreferencesFromCacheSync(this.context, options); 1176 } catch (err) { 1177 let code = (err as BusinessError).code; 1178 let message = (err as BusinessError).message; 1179 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 1180 } 1181 } 1182} 1183``` 1184 1185## Options<sup>10+</sup> 1186 1187Preferences实例配置选项。 1188 1189**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1190 1191| 名称 | 类型 | 必填 | 说明 | 1192| ----------- | ------ | ---- | ------------------------------------------------------------ | 1193| name | string | 是 | Preferences实例的名称。 | 1194| dataGroupId | string | 否 | 应用组ID,需要向应用市场获取。<br/>**模型约束:** 此属性仅在Stage模型下可用。<br/>从API version 10开始,支持此可选参数。指定在此dataGroupId对应的沙箱路径下创建Preferences实例,当此参数不填时,默认在本应用沙箱目录下创建Preferences实例。 | 1195 1196## Preferences 1197 1198首选项实例,提供获取和修改存储数据的接口。 1199 1200下列接口都需先使用[dataPreferences.getPreferences](#datapreferencesgetpreferences)获取到Preferences实例,再通过此实例调用对应接口。 1201 1202 1203### get 1204 1205get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void 1206 1207从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用callback异步回调。 1208 1209**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1210 1211**参数:** 1212 1213| 参数名 | 类型 | 必填 | 说明 | 1214| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1215| key | string | 是 | 要获取的存储Key名称,不能为空。 | 1216| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1217| callback | AsyncCallback<[ValueType](#valuetype)> | 是 | 回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误对象。 | 1218 1219**示例:** 1220 1221```ts 1222import {BusinessError} from '@ohos.base'; 1223 1224try { 1225 preferences.get('startup', 'default', (err: BusinessError, val: dataPreferences.ValueType) => { 1226 if (err) { 1227 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1228 return; 1229 } 1230 console.info("Succeeded in getting value of 'startup'. val: " + val); 1231 }) 1232} catch (err) { 1233 let code = (err as BusinessError).code; 1234 let message = (err as BusinessError).message; 1235 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1236} 1237``` 1238 1239 1240### get 1241 1242get(key: string, defValue: ValueType): Promise<ValueType> 1243 1244从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用Promise异步回调。 1245 1246**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1247 1248 **参数:** 1249 1250| 参数名 | 类型 | 必填 | 说明 | 1251| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1252| key | string | 是 | 要获取的存储Key名称,不能为空。 | 1253| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1254 1255**返回值:** 1256 1257| 类型 | 说明 | 1258| ----------------------------------- | ----------------------------- | 1259| Promise<[ValueType](#valuetype)> | Promise对象,返回键对应的值。 | 1260 1261**示例:** 1262 1263```ts 1264import {BusinessError} from '@ohos.base'; 1265 1266try { 1267 let promise = preferences.get('startup', 'default'); 1268 promise.then((data: dataPreferences.ValueType) => { 1269 console.info("Succeeded in getting value of 'startup'. Data: " + data); 1270 }).catch((err: BusinessError) => { 1271 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1272 }) 1273} catch (err) { 1274 let code = (err as BusinessError).code; 1275 let message = (err as BusinessError).message; 1276 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1277} 1278``` 1279 1280### getSync<sup>10+</sup> 1281 1282getSync(key: string, defValue: ValueType): ValueType 1283 1284从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,此为同步接口。 1285 1286**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1287 1288**参数:** 1289 1290| 参数名 | 类型 | 必填 | 说明 | 1291| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1292| key | string | 是 | 要获取的存储Key名称,不能为空。 | 1293| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1294 1295**返回值:** 1296 1297| 类型 | 说明 | 1298| ----------------------------------- | ----------------------------- | 1299| [ValueType](#valuetype) | 返回键对应的值。 | 1300 1301**示例:** 1302 1303```ts 1304try { 1305 let value: dataPreferences.ValueType = preferences.getSync('startup', 'default'); 1306 console.info("Succeeded in getting value of 'startup'. Data: " + value); 1307} catch (err) { 1308 let code = (err as BusinessError).code; 1309 let message = (err as BusinessError).message; 1310 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1311} 1312``` 1313 1314### getAll 1315 1316getAll(callback: AsyncCallback<Object>): void; 1317 1318从缓存的Preferences实例中获取所有键值数据。 1319 1320**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1321 1322**参数:** 1323 1324| 参数名 | 类型 | 必填 | 说明 | 1325| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1326| callback | AsyncCallback<Object> | 是 | 回调函数。当获取成功,err为undefined,value为所有键值数据;否则err为错误对象。 | 1327 1328**示例:** 1329 1330```ts 1331import {BusinessError} from '@ohos.base'; 1332 1333// 由于ArkTS中无Object.keys,且无法使用for..in... 1334// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1335function getObjKeys(obj: Object): string[] { 1336 let keys = Object.keys(obj); 1337 return keys; 1338} 1339 1340try { 1341 preferences.getAll((err: BusinessError, value: Object) => { 1342 if (err) { 1343 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1344 return; 1345 } 1346 let allKeys = getObjKeys(value); 1347 console.info("getAll keys = " + allKeys); 1348 console.info("getAll object = " + JSON.stringify(value)); 1349 }) 1350} catch (err) { 1351 let code = (err as BusinessError).code; 1352 let message = (err as BusinessError).message; 1353 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1354} 1355``` 1356 1357 1358### getAll 1359 1360getAll(): Promise<Object> 1361 1362从缓存的Preferences实例中获取所有键值数据。 1363 1364**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1365 1366**返回值:** 1367 1368| 类型 | 说明 | 1369| --------------------- | ------------------------------------------- | 1370| Promise<Object> | Promise对象,返回含有所有键值数据。 | 1371 1372**示例:** 1373 1374```ts 1375import {BusinessError} from '@ohos.base'; 1376 1377// 由于ArkTS中无Object.keys,且无法使用for..in... 1378// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1379function getObjKeys(obj: Object): string[] { 1380 let keys = Object.keys(obj); 1381 return keys; 1382} 1383 1384try { 1385 let promise = preferences.getAll(); 1386 promise.then((value: Object) => { 1387 let allKeys = getObjKeys(value); 1388 console.info('getAll keys = ' + allKeys); 1389 console.info("getAll object = " + JSON.stringify(value)); 1390 }).catch((err: BusinessError) => { 1391 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1392 }) 1393} catch (err) { 1394 let code = (err as BusinessError).code; 1395 let message = (err as BusinessError).message; 1396 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1397} 1398``` 1399 1400### getAllSync<sup>10+</sup> 1401 1402getAllSync(): Object 1403 1404从缓存的Preferences实例中获取所有键值数据,此为同步接口。 1405 1406**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1407 1408**返回值:** 1409 1410| 类型 | 说明 | 1411| --------------------- | ------------------------------------------- | 1412| Object | 返回含有所有键值数据。 | 1413 1414**示例:** 1415 1416```ts 1417// 由于ArkTS中无Object.keys,且无法使用for..in... 1418// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1419function getObjKeys(obj: Object): string[] { 1420 let keys = Object.keys(obj); 1421 return keys; 1422} 1423 1424try { 1425 let value = preferences.getAllSync(); 1426 let allKeys = getObjKeys(value); 1427 console.info('getAll keys = ' + allKeys); 1428 console.info("getAll object = " + JSON.stringify(value)); 1429} catch (err) { 1430 let code = (err as BusinessError).code; 1431 let message = (err as BusinessError).message; 1432 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1433} 1434``` 1435 1436### put 1437 1438put(key: string, value: ValueType, callback: AsyncCallback<void>): void 1439 1440将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1441 1442 > **说明:** 1443 > 1444 > 当对应的键已经存在时,put()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。 1445 1446**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1447 1448**参数:** 1449 1450| 参数名 | 类型 | 必填 | 说明 | 1451| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1452| key | string | 是 | 要修改的存储的Key,不能为空。 | 1453| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1454| callback | AsyncCallback<void> | 是 | 回调函数。当数据写入成功,err为undefined;否则为错误对象。 | 1455 1456**示例:** 1457 1458```ts 1459import {BusinessError} from '@ohos.base'; 1460 1461try { 1462 preferences.put('startup', 'auto', (err: BusinessError) => { 1463 if (err) { 1464 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1465 return; 1466 } 1467 console.info("Succeeded in putting value of 'startup'."); 1468 }) 1469} catch (err) { 1470 let code = (err as BusinessError).code; 1471 let message = (err as BusinessError).message; 1472 console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message); 1473} 1474``` 1475 1476 1477### put 1478 1479put(key: string, value: ValueType): Promise<void> 1480 1481将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1482 1483 > **说明:** 1484 > 1485 > 当对应的键已经存在时,put()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。 1486 1487**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1488 1489**参数:** 1490 1491| 参数名 | 类型 | 必填 | 说明 | 1492| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1493| key | string | 是 | 要修改的存储的Key,不能为空。 | 1494| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1495 1496**返回值:** 1497 1498| 类型 | 说明 | 1499| ------------------- | ------------------------- | 1500| Promise<void> | 无返回结果的Promise对象。 | 1501 1502**示例:** 1503 1504```ts 1505import {BusinessError} from '@ohos.base'; 1506 1507try { 1508 let promise = preferences.put('startup', 'auto'); 1509 promise.then(() => { 1510 console.info("Succeeded in putting value of 'startup'."); 1511 }).catch((err: BusinessError) => { 1512 console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); 1513 }) 1514} catch (err) { 1515 let code = (err as BusinessError).code; 1516 let message = (err as BusinessError).message; 1517 console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); 1518} 1519``` 1520 1521 1522### putSync<sup>10+</sup> 1523 1524putSync(key: string, value: ValueType): void 1525 1526将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1527 1528 > **说明:** 1529 > 1530 > 当对应的键已经存在时,putSync()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。 1531 1532**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1533 1534**参数:** 1535 1536| 参数名 | 类型 | 必填 | 说明 | 1537| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1538| key | string | 是 | 要修改的存储的Key,不能为空。 | 1539| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1540 1541**示例:** 1542 1543```ts 1544try { 1545 preferences.putSync('startup', 'auto'); 1546} catch (err) { 1547 let code = (err as BusinessError).code; 1548 let message = (err as BusinessError).message; 1549 console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); 1550} 1551``` 1552 1553 1554### has 1555 1556has(key: string, callback: AsyncCallback<boolean>): void 1557 1558检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用callback异步回调。 1559 1560**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1561 1562**参数:** 1563 1564| 参数名 | 类型 | 必填 | 说明 | 1565| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | 1566| key | string | 是 | 要检查的存储key名称,不能为空。 | 1567| callback | AsyncCallback<boolean> | 是 | 回调函数。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1568 1569**示例:** 1570 1571```ts 1572import {BusinessError} from '@ohos.base'; 1573 1574try { 1575 preferences.has('startup', (err: BusinessError, val: boolean) => { 1576 if (err) { 1577 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1578 return; 1579 } 1580 if (val) { 1581 console.info("The key 'startup' is contained."); 1582 } else { 1583 console.info("The key 'startup' dose not contain."); 1584 } 1585 }) 1586} catch (err) { 1587 let code = (err as BusinessError).code; 1588 let message = (err as BusinessError).message; 1589 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1590} 1591``` 1592 1593 1594### has 1595 1596has(key: string): Promise<boolean> 1597 1598检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用Promise异步回调。 1599 1600**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1601 1602**参数:** 1603 1604| 参数名 | 类型 | 必填 | 说明 | 1605| ------ | ------ | ---- | ------------------------------- | 1606| key | string | 是 | 要检查的存储key名称,不能为空。 | 1607 1608**返回值:** 1609 1610| 类型 | 说明 | 1611| ---------------------- | ------------------------------------------------------------ | 1612| Promise<boolean> | Promise对象。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1613 1614**示例:** 1615 1616```ts 1617import {BusinessError} from '@ohos.base'; 1618 1619try { 1620 let promise = preferences.has('startup'); 1621 promise.then((val: boolean) => { 1622 if (val) { 1623 console.info("The key 'startup' is contained."); 1624 } else { 1625 console.info("The key 'startup' dose not contain."); 1626 } 1627 }).catch((err: BusinessError) => { 1628 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1629 }) 1630} catch (err) { 1631 let code = (err as BusinessError).code; 1632 let message = (err as BusinessError).message; 1633 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1634} 1635``` 1636 1637 1638### hasSync<sup>10+</sup> 1639 1640hasSync(key: string): boolean 1641 1642检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,此为同步接口。 1643 1644**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1645 1646**参数:** 1647 1648| 参数名 | 类型 | 必填 | 说明 | 1649| ------ | ------ | ---- | ------------------------------- | 1650| key | string | 是 | 要检查的存储key名称,不能为空。 | 1651 1652**返回值:** 1653 1654| 类型 | 说明 | 1655| ---------------------- | ------------------------------------------------------------ | 1656| boolean | 返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1657 1658**示例:** 1659 1660```ts 1661try { 1662 let isExist: boolean = preferences.hasSync('startup'); 1663 if (isExist) { 1664 console.info("The key 'startup' is contained."); 1665 } else { 1666 console.info("The key 'startup' dose not contain."); 1667 } 1668} catch (err) { 1669 let code = (err as BusinessError).code; 1670 let message = (err as BusinessError).message; 1671 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1672} 1673``` 1674 1675 1676### delete 1677 1678delete(key: string, callback: AsyncCallback<void>): void 1679 1680从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1681 1682**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1683 1684**参数:** 1685 1686| 参数名 | 类型 | 必填 | 说明 | 1687| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1688| key | string | 是 | 要删除的存储Key名称,不能为空。 | 1689| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功,err为undefined;否则为错误对象。 | 1690 1691**示例:** 1692 1693```ts 1694import {BusinessError} from '@ohos.base'; 1695 1696try { 1697 preferences.delete('startup', (err: BusinessError) => { 1698 if (err) { 1699 console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); 1700 return; 1701 } 1702 console.info("Succeeded in deleting the key 'startup'."); 1703 }) 1704} catch (err) { 1705 let code = (err as BusinessError).code; 1706 let message = (err as BusinessError).message; 1707 console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message); 1708} 1709``` 1710 1711 1712### delete 1713 1714delete(key: string): Promise<void> 1715 1716从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1717 1718**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1719 1720**参数:** 1721 1722| 参数名 | 类型 | 必填 | 说明 | 1723| ------ | ------ | ---- | ------------------------------- | 1724| key | string | 是 | 要删除的存储key名称,不能为空。 | 1725 1726**返回值:** 1727 1728| 类型 | 说明 | 1729| ------------------- | ------------------------- | 1730| Promise<void> | 无返回结果的Promise对象。 | 1731 1732**示例:** 1733 1734```ts 1735import {BusinessError} from '@ohos.base'; 1736 1737try { 1738 let promise = preferences.delete('startup'); 1739 promise.then(() => { 1740 console.info("Succeeded in deleting the key 'startup'."); 1741 }).catch((err: BusinessError) => { 1742 console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); 1743 }) 1744} catch (err) { 1745 let code = (err as BusinessError).code; 1746 let message = (err as BusinessError).message; 1747 console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); 1748} 1749``` 1750 1751 1752### deleteSync<sup>10+</sup> 1753 1754deleteSync(key: string): void 1755 1756从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1757 1758**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1759 1760**参数:** 1761 1762| 参数名 | 类型 | 必填 | 说明 | 1763| ------ | ------ | ---- | ------------------------------- | 1764| key | string | 是 | 要删除的存储key名称,不能为空。 | 1765 1766**示例:** 1767 1768```ts 1769try { 1770 preferences.deleteSync('startup'); 1771} catch (err) { 1772 let code = (err as BusinessError).code; 1773 let message = (err as BusinessError).message; 1774 console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); 1775} 1776``` 1777 1778 1779### flush 1780 1781flush(callback: AsyncCallback<void>): void 1782 1783将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用callback异步回调。 1784 1785**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1786 1787**参数:** 1788 1789| 参数名 | 类型 | 必填 | 说明 | 1790| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1791| callback | AsyncCallback<void> | 是 | 回调函数。当保存成功,err为undefined;否则为错误对象。 | 1792 1793**示例:** 1794 1795```ts 1796import {BusinessError} from '@ohos.base'; 1797 1798try { 1799 preferences.flush((err: BusinessError) => { 1800 if (err) { 1801 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1802 return; 1803 } 1804 console.info("Succeeded in flushing."); 1805 }) 1806} catch (err) { 1807 let code = (err as BusinessError).code; 1808 let message = (err as BusinessError).message; 1809 console.error("Failed to flush. code =" + code + ", message =" + message); 1810} 1811``` 1812 1813 1814### flush 1815 1816flush(): Promise<void> 1817 1818将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 1819 1820**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1821 1822**返回值:** 1823 1824| 类型 | 说明 | 1825| ------------------- | ------------------------- | 1826| Promise<void> | 无返回结果的Promise对象。 | 1827 1828**示例:** 1829 1830```ts 1831import {BusinessError} from '@ohos.base'; 1832 1833try { 1834 let promise = preferences.flush(); 1835 promise.then(() => { 1836 console.info("Succeeded in flushing."); 1837 }).catch((err: BusinessError) => { 1838 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1839 }) 1840} catch (err) { 1841 let code = (err as BusinessError).code; 1842 let message = (err as BusinessError).message; 1843 console.error("Failed to flush. code =" + code + ", message =" + message); 1844} 1845``` 1846 1847 1848### clear 1849 1850clear(callback: AsyncCallback<void>): void 1851 1852清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1853 1854**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1855 1856**参数:** 1857 1858| 参数名 | 类型 | 必填 | 说明 | 1859| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1860| callback | AsyncCallback<void> | 是 | 回调函数。当清除成功,err为undefined;否则为错误对象。 | 1861 1862**示例:** 1863 1864```ts 1865import {BusinessError} from '@ohos.base'; 1866 1867try { 1868 preferences.clear((err: BusinessError) =>{ 1869 if (err) { 1870 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1871 return; 1872 } 1873 console.info("Succeeded in clearing."); 1874 }) 1875} catch (err) { 1876 let code = (err as BusinessError).code; 1877 let message = (err as BusinessError).message; 1878 console.error("Failed to clear. code =" + code + ", message =" + message); 1879} 1880``` 1881 1882 1883### clear 1884 1885clear(): Promise<void> 1886 1887清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1888 1889**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1890 1891**返回值:** 1892 1893| 类型 | 说明 | 1894| ------------------- | ------------------------- | 1895| Promise<void> | 无返回结果的Promise对象。 | 1896 1897**示例:** 1898 1899```ts 1900import {BusinessError} from '@ohos.base'; 1901 1902try { 1903 let promise = preferences.clear(); 1904 promise.then(() => { 1905 console.info("Succeeded in clearing."); 1906 }).catch((err: BusinessError) => { 1907 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1908 }) 1909} catch (err) { 1910 let code = (err as BusinessError).code; 1911 let message = (err as BusinessError).message; 1912 console.error("Failed to clear. code =" + code + ", message =" + message); 1913} 1914``` 1915 1916 1917### clearSync<sup>10+</sup> 1918 1919clearSync(): void 1920 1921清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1922 1923**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1924 1925**示例:** 1926 1927```ts 1928try { 1929 preferences.clearSync(); 1930} catch (err) { 1931 let code = (err as BusinessError).code; 1932 let message = (err as BusinessError).message; 1933 console.error("Failed to clear. code =" + code + ", message =" + message); 1934} 1935``` 1936 1937 1938### on('change') 1939 1940on(type: 'change', callback: ( key : string ) => void): void 1941 1942订阅数据变更,订阅的Key的值发生变更后,在执行[flush](#flush)方法后,触发callback回调。 1943 1944**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1945 1946**参数:** 1947 1948| 参数名 | 类型 | 必填 | 说明 | 1949| -------- | -------- | ---- | ---------------------------------------- | 1950| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | 1951| callback | Function | 是 | 回调函数。<br />key: 发生变化的Key。 | 1952 1953**示例:** 1954 1955```ts 1956import {BusinessError} from '@ohos.base'; 1957 1958let observer = (key: string) => { 1959 console.info("The key " + key + " changed."); 1960} 1961preferences.on('change', observer); 1962preferences.putSync('startup', 'manual'); 1963preferences.flush((err: BusinessError) => { 1964 if (err) { 1965 console.error("Failed to flush. Cause: " + err); 1966 return; 1967 } 1968 console.info("Succeeded in flushing."); 1969}) 1970``` 1971 1972### on('multiProcessChange')<sup>10+</sup> 1973 1974on(type: 'multiProcessChange', callback: ( key : string ) => void): void 1975 1976订阅进程间数据变更,多个进程持有同一个首选项文件时,订阅的Key的值在任意一个进程发生变更后,执行[flush](#flush)方法后,触发callback回调。 1977 1978**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1979 1980**参数:** 1981 1982| 参数名 | 类型 | 必填 | 说明 | 1983| -------- | -------- | ---- | ------------------------------------------------------------ | 1984| type | string | 是 | 事件类型,固定值'multiProcessChange',表示多进程间的数据变更。 | 1985| callback | Function | 是 | 回调函数。<br />key: 发生变化的Key。 | 1986 1987**错误码:** 1988 1989以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 1990 1991| 错误码ID | 错误信息 | 1992| -------- | -------------------------------------- | 1993| 15500019 | Failed to obtain subscription service. | 1994 1995**示例:** 1996 1997```ts 1998import {BusinessError} from '@ohos.base'; 1999 2000let observer = (key: string) => { 2001 console.info("The key " + key + " changed."); 2002} 2003preferences.on('multiProcessChange', observer); 2004preferences.putSync('startup', 'manual'); 2005preferences.flush((err: BusinessError) => { 2006 if (err) { 2007 console.error("Failed to flush. Cause: " + err); 2008 return; 2009 } 2010 console.info("Succeeded in flushing."); 2011}) 2012``` 2013 2014### off('change') 2015 2016off(type: 'change', callback?: ( key : string ) => void): void 2017 2018取消订阅数据变更。 2019 2020**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2021 2022**参数:** 2023 2024| 参数名 | 类型 | 必填 | 说明 | 2025| -------- | -------- | ---- | ------------------------------------------------------------ | 2026| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | 2027| callback | Function | 否 | 需要取消的回调函数,不填写则全部取消。<br />key: 发生变化的Key。 | 2028 2029**示例:** 2030 2031```ts 2032import {BusinessError} from '@ohos.base'; 2033 2034let observer = (key: string) => { 2035 console.info("The key " + key + " changed."); 2036} 2037preferences.on('change', observer); 2038preferences.putSync('startup', 'auto'); 2039preferences.flush((err: BusinessError) => { 2040 if (err) { 2041 console.error("Failed to flush. Cause: " + err); 2042 return; 2043 } 2044 console.info("Succeeded in flushing."); 2045}) 2046preferences.off('change', observer); 2047``` 2048 2049### off('multiProcessChange')<sup>10+</sup> 2050 2051off(type: 'multiProcessChange', callback?: ( key : string ) => void): void 2052 2053取消订阅进程间数据变更。 2054 2055**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2056 2057**参数:** 2058 2059| 参数名 | 类型 | 必填 | 说明 | 2060| -------- | -------- | ---- | ------------------------------------------------------------ | 2061| type | string | 是 | 事件类型,固定值'multiProcessChange',表示多进程间的数据变更。 | 2062| callback | Function | 否 | 需要取消的回调函数,不填写则全部取消。<br />key: 发生变化的Key。 | 2063 2064**示例:** 2065 2066```ts 2067import {BusinessError} from '@ohos.base'; 2068 2069let observer = (key: string) => { 2070 console.info("The key " + key + " changed."); 2071} 2072preferences.on('multiProcessChange', observer); 2073preferences.putSync('startup', 'auto'); 2074preferences.flush((err: BusinessError) => { 2075 if (err) { 2076 console.error("Failed to flush. Cause: " + err); 2077 return; 2078 } 2079 console.info("Succeeded in flushing."); 2080}) 2081preferences.off('multiProcessChange', observer); 2082``` 2083## ValueType 2084 2085用于表示允许的数据字段类型。 2086 2087**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2088 2089| 类型 | 说明 | 2090| --------------- | ------------------------------ | 2091| number | 表示值类型为数字。 | 2092| string | 表示值类型为字符串。 | 2093| boolean | 表示值类型为布尔值。 | 2094| Array\<number> | 表示值类型为数字类型的数组。 | 2095| Array\<boolean> | 表示值类型为布尔类型的数组。 | 2096| Array\<string> | 表示值类型为字符串类型的数组。 | 2097