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 data_preferences 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## data_preferences.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: data_preferences.Preferences | null = null; 56 57try { 58 data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.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: data_preferences.Preferences | null = null; 81 82class EntryAbility extends UIAbility { 83 onWindowStageCreate(windowStage: window.WindowStage) { 84 try { 85 data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.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## data_preferences.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: data_preferences.Preferences | null = null; 135try { 136 let promise = data_preferences.getPreferences(context, 'myStore'); 137 promise.then((object: data_preferences.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: data_preferences.Preferences | null = null; 158 159class EntryAbility extends UIAbility { 160 onWindowStageCreate(windowStage: window.WindowStage) { 161 try { 162 let promise = data_preferences.getPreferences(this.context, 'myStore'); 163 promise.then((object: data_preferences.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## data_preferences.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: data_preferences.Preferences | null = null; 214 215try { 216 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 217 data_preferences.getPreferences(context, options, (err: BusinessError, val: data_preferences.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: data_preferences.Preferences | null = null; 241 242class EntryAbility extends UIAbility { 243 onWindowStageCreate(windowStage: window.WindowStage) { 244 try { 245 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 246 data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.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## data_preferences.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: data_preferences.Preferences | null = null; 304try { 305 let options: data_preferences.Options = { name: 'myStore' }; 306 let promise = data_preferences.getPreferences(context, options); 307 promise.then((object: data_preferences.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: data_preferences.Preferences | null = null; 328 329class EntryAbility extends UIAbility { 330 onWindowStageCreate(windowStage: window.WindowStage) { 331 try { 332 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 333 let promise = data_preferences.getPreferences(this.context, options); 334 promise.then((object: data_preferences.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## data_preferences.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: data_preferences.Preferences | null = null; 390 391try { 392 let options: data_preferences.Options = { name: 'myStore' }; 393 preferences = data_preferences.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: data_preferences.Preferences | null = null; 409 410class EntryAbility extends UIAbility { 411 onWindowStageCreate(windowStage: window.WindowStage) { 412 try { 413 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 414 preferences = data_preferences.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## data_preferences.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 data_preferences.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 data_preferences.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## data_preferences.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 = data_preferences.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 = data_preferences.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## data_preferences.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: data_preferences.Options = { name: 'myStore' }; 624 data_preferences.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: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 649 data_preferences.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## data_preferences.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: data_preferences.Options = { name: 'myStore' }; 712 let promise = data_preferences.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: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 736 let promise = data_preferences.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## data_preferences.removePreferencesFromCache 753 754removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void 755 756从缓存中移出指定的Preferences实例,使用callback异步回调。 757 758应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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 data_preferences.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 data_preferences.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## data_preferences.removePreferencesFromCache 824 825removePreferencesFromCache(context: Context, name: string): Promise<void> 826 827从缓存中移出指定的Preferences实例,使用Promise异步回调。 828 829应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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 = data_preferences.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 = data_preferences.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## data_preferences.removePreferencesFromCacheSync<sup>10+</sup> 898 899removePreferencesFromCacheSync(context: Context, name: string): void 900 901从缓存中移出指定的Preferences实例,此为同步接口。 902 903应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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 data_preferences.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 data_preferences.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## data_preferences.removePreferencesFromCache<sup>10+</sup> 955 956removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void 957 958从缓存中移出指定的Preferences实例,使用callback异步回调。 959 960应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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: data_preferences.Options = { name: 'myStore' }; 994 data_preferences.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: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1019 data_preferences.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## data_preferences.removePreferencesFromCache<sup>10+</sup> 1036 1037removePreferencesFromCache(context: Context, options: Options): Promise<void> 1038 1039从缓存中移出指定的Preferences实例,使用Promise异步回调。 1040 1041应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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: data_preferences.Options = { name: 'myStore' }; 1080 let promise = data_preferences.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: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1104 let promise = data_preferences.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## data_preferences.removePreferencesFromCacheSync<sup>10+</sup> 1120 1121removePreferencesFromCacheSync(context: Context, options: Options):void 1122 1123从缓存中移出指定的Preferences实例,此为同步接口。 1124 1125应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取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: data_preferences.Options = { name: 'myStore' }; 1157 data_preferences.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: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1175 data_preferences.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下列接口都需先使用[data_preferences.getPreferences](#data_preferencesgetpreferences)获取到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 1222try { 1223 preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { 1224 if (err) { 1225 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1226 return; 1227 } 1228 console.info("Succeeded in getting value of 'startup'. val: " + val); 1229 }) 1230} catch (err) { 1231 let code = (err as BusinessError).code; 1232 let message = (err as BusinessError).message; 1233 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1234} 1235``` 1236 1237 1238### get 1239 1240get(key: string, defValue: ValueType): Promise<ValueType> 1241 1242从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用Promise异步回调。 1243 1244**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1245 1246 **参数:** 1247 1248| 参数名 | 类型 | 必填 | 说明 | 1249| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1250| key | string | 是 | 要获取的存储Key名称,不能为空。 | 1251| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1252 1253**返回值:** 1254 1255| 类型 | 说明 | 1256| ----------------------------------- | ----------------------------- | 1257| Promise<[ValueType](#valuetype)> | Promise对象,返回键对应的值。 | 1258 1259**示例:** 1260 1261```ts 1262try { 1263 let promise = preferences.get('startup', 'default'); 1264 promise.then((data: data_preferences.ValueType) => { 1265 console.info("Succeeded in getting value of 'startup'. Data: " + data); 1266 }).catch((err: BusinessError) => { 1267 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1268 }) 1269} catch (err) { 1270 let code = (err as BusinessError).code; 1271 let message = (err as BusinessError).message; 1272 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1273} 1274``` 1275 1276### getSync<sup>10+</sup> 1277 1278getSync(key: string, defValue: ValueType): ValueType 1279 1280从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,此为同步接口。 1281 1282**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1283 1284**参数:** 1285 1286| 参数名 | 类型 | 必填 | 说明 | 1287| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1288| key | string | 是 | 要获取的存储Key名称,不能为空。 | 1289| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1290 1291**返回值:** 1292 1293| 类型 | 说明 | 1294| ----------------------------------- | ----------------------------- | 1295| [ValueType](#valuetype) | 返回键对应的值。 | 1296 1297**示例:** 1298 1299```ts 1300try { 1301 let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); 1302 console.info("Succeeded in getting value of 'startup'. Data: " + value); 1303} catch (err) { 1304 let code = (err as BusinessError).code; 1305 let message = (err as BusinessError).message; 1306 console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); 1307} 1308``` 1309 1310### getAll 1311 1312getAll(callback: AsyncCallback<Object>): void; 1313 1314从缓存的Preferences实例中获取所有键值数据。 1315 1316**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1317 1318**参数:** 1319 1320| 参数名 | 类型 | 必填 | 说明 | 1321| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1322| callback | AsyncCallback<Object> | 是 | 回调函数。当获取成功,err为undefined,value为所有键值数据;否则err为错误对象。 | 1323 1324**示例:** 1325 1326```ts 1327// 由于ArkTS中无Object.keys,且无法使用for..in... 1328// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1329function getObjKeys(obj: Object): string[] { 1330 let keys = Object.keys(obj); 1331 return keys; 1332} 1333 1334try { 1335 preferences.getAll((err: BusinessError, value: Object) => { 1336 if (err) { 1337 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1338 return; 1339 } 1340 let allKeys = getObjKeys(value); 1341 console.info("getAll keys = " + allKeys); 1342 console.info("getAll object = " + JSON.stringify(value)); 1343 }) 1344} catch (err) { 1345 let code = (err as BusinessError).code; 1346 let message = (err as BusinessError).message; 1347 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1348} 1349``` 1350 1351 1352### getAll 1353 1354getAll(): Promise<Object> 1355 1356从缓存的Preferences实例中获取所有键值数据。 1357 1358**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1359 1360**返回值:** 1361 1362| 类型 | 说明 | 1363| --------------------- | ------------------------------------------- | 1364| Promise<Object> | Promise对象,返回含有所有键值数据。 | 1365 1366**示例:** 1367 1368```ts 1369// 由于ArkTS中无Object.keys,且无法使用for..in... 1370// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1371function getObjKeys(obj: Object): string[] { 1372 let keys = Object.keys(obj); 1373 return keys; 1374} 1375 1376try { 1377 let promise = preferences.getAll(); 1378 promise.then((value: Object) => { 1379 let allKeys = getObjKeys(value); 1380 console.info('getAll keys = ' + allKeys); 1381 console.info("getAll object = " + JSON.stringify(value)); 1382 }).catch((err: BusinessError) => { 1383 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1384 }) 1385} catch (err) { 1386 let code = (err as BusinessError).code; 1387 let message = (err as BusinessError).message; 1388 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1389} 1390``` 1391 1392### getAllSync<sup>10+</sup> 1393 1394getAllSync(): Object 1395 1396从缓存的Preferences实例中获取所有键值数据。,此为同步接口。 1397 1398**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1399 1400**返回值:** 1401 1402| 类型 | 说明 | 1403| --------------------- | ------------------------------------------- | 1404| Object | 返回含有所有键值数据。 | 1405 1406**示例:** 1407 1408```ts 1409// 由于ArkTS中无Object.keys,且无法使用for..in... 1410// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 1411function getObjKeys(obj: Object): string[] { 1412 let keys = Object.keys(obj); 1413 return keys; 1414} 1415 1416try { 1417 let value = preferences.getAllSync(); 1418 let allKeys = getObjKeys(value); 1419 console.info('getAll keys = ' + allKeys); 1420 console.info("getAll object = " + JSON.stringify(value)); 1421} catch (err) { 1422 let code = (err as BusinessError).code; 1423 let message = (err as BusinessError).message; 1424 console.error("Failed to get all key-values. code =" + code + ", message =" + message); 1425} 1426``` 1427 1428### put 1429 1430put(key: string, value: ValueType, callback: AsyncCallback<void>): void 1431 1432将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1433 1434**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1435 1436**参数:** 1437 1438| 参数名 | 类型 | 必填 | 说明 | 1439| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1440| key | string | 是 | 要修改的存储的Key,不能为空。 | 1441| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1442| callback | AsyncCallback<void> | 是 | 回调函数。当数据写入成功,err为undefined;否则为错误对象。 | 1443 1444**示例:** 1445 1446```ts 1447try { 1448 preferences.put('startup', 'auto', (err: BusinessError) => { 1449 if (err) { 1450 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1451 return; 1452 } 1453 console.info("Succeeded in putting value of 'startup'."); 1454 }) 1455} catch (err) { 1456 let code = (err as BusinessError).code; 1457 let message = (err as BusinessError).message; 1458 console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message); 1459} 1460``` 1461 1462 1463### put 1464 1465put(key: string, value: ValueType): Promise<void> 1466 1467将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1468 1469**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1470 1471**参数:** 1472 1473| 参数名 | 类型 | 必填 | 说明 | 1474| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1475| key | string | 是 | 要修改的存储的Key,不能为空。 | 1476| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1477 1478**返回值:** 1479 1480| 类型 | 说明 | 1481| ------------------- | ------------------------- | 1482| Promise<void> | 无返回结果的Promise对象。 | 1483 1484**示例:** 1485 1486```ts 1487try { 1488 let promise = preferences.put('startup', 'auto'); 1489 promise.then(() => { 1490 console.info("Succeeded in putting value of 'startup'."); 1491 }).catch((err: BusinessError) => { 1492 console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); 1493 }) 1494} catch (err) { 1495 let code = (err as BusinessError).code; 1496 let message = (err as BusinessError).message; 1497 console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); 1498} 1499``` 1500 1501 1502### putSync<sup>10+</sup> 1503 1504putSync(key: string, value: ValueType): void 1505 1506将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1507 1508**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1509 1510**参数:** 1511 1512| 参数名 | 类型 | 必填 | 说明 | 1513| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1514| key | string | 是 | 要修改的存储的Key,不能为空。 | 1515| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 | 1516 1517**示例:** 1518 1519```ts 1520try { 1521 preferences.putSync('startup', 'auto'); 1522} catch (err) { 1523 let code = (err as BusinessError).code; 1524 let message = (err as BusinessError).message; 1525 console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); 1526} 1527``` 1528 1529 1530### has 1531 1532has(key: string, callback: AsyncCallback<boolean>): void 1533 1534检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用callback异步回调。 1535 1536**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1537 1538**参数:** 1539 1540| 参数名 | 类型 | 必填 | 说明 | 1541| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | 1542| key | string | 是 | 要检查的存储key名称,不能为空。 | 1543| callback | AsyncCallback<boolean> | 是 | 回调函数。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1544 1545**示例:** 1546 1547```ts 1548try { 1549 preferences.has('startup', (err: BusinessError, val: boolean) => { 1550 if (err) { 1551 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1552 return; 1553 } 1554 if (val) { 1555 console.info("The key 'startup' is contained."); 1556 } else { 1557 console.info("The key 'startup' dose not contain."); 1558 } 1559 }) 1560} catch (err) { 1561 let code = (err as BusinessError).code; 1562 let message = (err as BusinessError).message; 1563 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1564} 1565``` 1566 1567 1568### has 1569 1570has(key: string): Promise<boolean> 1571 1572检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用Promise异步回调。 1573 1574**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1575 1576**参数:** 1577 1578| 参数名 | 类型 | 必填 | 说明 | 1579| ------ | ------ | ---- | ------------------------------- | 1580| key | string | 是 | 要检查的存储key名称,不能为空。 | 1581 1582**返回值:** 1583 1584| 类型 | 说明 | 1585| ---------------------- | ------------------------------------------------------------ | 1586| Promise<boolean> | Promise对象。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1587 1588**示例:** 1589 1590```ts 1591try { 1592 let promise = preferences.has('startup'); 1593 promise.then((val: boolean) => { 1594 if (val) { 1595 console.info("The key 'startup' is contained."); 1596 } else { 1597 console.info("The key 'startup' dose not contain."); 1598 } 1599 }).catch((err: BusinessError) => { 1600 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1601 }) 1602} catch (err) { 1603 let code = (err as BusinessError).code; 1604 let message = (err as BusinessError).message; 1605 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1606} 1607``` 1608 1609 1610### hasSync<sup>10+</sup> 1611 1612hasSync(key: string): boolean 1613 1614检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,此为同步接口。 1615 1616**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1617 1618**参数:** 1619 1620| 参数名 | 类型 | 必填 | 说明 | 1621| ------ | ------ | ---- | ------------------------------- | 1622| key | string | 是 | 要检查的存储key名称,不能为空。 | 1623 1624**返回值:** 1625 1626| 类型 | 说明 | 1627| ---------------------- | ------------------------------------------------------------ | 1628| boolean | 返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | 1629 1630**示例:** 1631 1632```ts 1633try { 1634 let isExist: boolean = preferences.hasSync('startup'); 1635 if (isExist) { 1636 console.info("The key 'startup' is contained."); 1637 } else { 1638 console.info("The key 'startup' dose not contain."); 1639 } 1640} catch (err) { 1641 let code = (err as BusinessError).code; 1642 let message = (err as BusinessError).message; 1643 console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); 1644} 1645``` 1646 1647 1648### delete 1649 1650delete(key: string, callback: AsyncCallback<void>): void 1651 1652从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1653 1654**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1655 1656**参数:** 1657 1658| 参数名 | 类型 | 必填 | 说明 | 1659| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1660| key | string | 是 | 要删除的存储Key名称,不能为空。 | 1661| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功,err为undefined;否则为错误对象。 | 1662 1663**示例:** 1664 1665```ts 1666try { 1667 preferences.delete('startup', (err: BusinessError) => { 1668 if (err) { 1669 console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); 1670 return; 1671 } 1672 console.info("Succeeded in deleting the key 'startup'."); 1673 }) 1674} catch (err) { 1675 let code = (err as BusinessError).code; 1676 let message = (err as BusinessError).message; 1677 console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message); 1678} 1679``` 1680 1681 1682### delete 1683 1684delete(key: string): Promise<void> 1685 1686从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1687 1688**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1689 1690**参数:** 1691 1692| 参数名 | 类型 | 必填 | 说明 | 1693| ------ | ------ | ---- | ------------------------------- | 1694| key | string | 是 | 要删除的存储key名称,不能为空。 | 1695 1696**返回值:** 1697 1698| 类型 | 说明 | 1699| ------------------- | ------------------------- | 1700| Promise<void> | 无返回结果的Promise对象。 | 1701 1702**示例:** 1703 1704```ts 1705try { 1706 let promise = preferences.delete('startup'); 1707 promise.then(() => { 1708 console.info("Succeeded in deleting the key 'startup'."); 1709 }).catch((err: BusinessError) => { 1710 console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); 1711 }) 1712} catch (err) { 1713 let code = (err as BusinessError).code; 1714 let message = (err as BusinessError).message; 1715 console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); 1716} 1717``` 1718 1719 1720### deleteSync<sup>10+</sup> 1721 1722deleteSync(key: string): void 1723 1724从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1725 1726**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1727 1728**参数:** 1729 1730| 参数名 | 类型 | 必填 | 说明 | 1731| ------ | ------ | ---- | ------------------------------- | 1732| key | string | 是 | 要删除的存储key名称,不能为空。 | 1733 1734**示例:** 1735 1736```ts 1737try { 1738 preferences.deleteSync('startup'); 1739} catch (err) { 1740 let code = (err as BusinessError).code; 1741 let message = (err as BusinessError).message; 1742 console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); 1743} 1744``` 1745 1746 1747### flush 1748 1749flush(callback: AsyncCallback<void>): void 1750 1751将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用callback异步回调。 1752 1753**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1754 1755**参数:** 1756 1757| 参数名 | 类型 | 必填 | 说明 | 1758| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1759| callback | AsyncCallback<void> | 是 | 回调函数。当保存成功,err为undefined;否则为错误对象。 | 1760 1761**示例:** 1762 1763```ts 1764try { 1765 preferences.flush((err: BusinessError) => { 1766 if (err) { 1767 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1768 return; 1769 } 1770 console.info("Succeeded in flushing."); 1771 }) 1772} catch (err) { 1773 let code = (err as BusinessError).code; 1774 let message = (err as BusinessError).message; 1775 console.error("Failed to flush. code =" + code + ", message =" + message); 1776} 1777``` 1778 1779 1780### flush 1781 1782flush(): Promise<void> 1783 1784将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 1785 1786**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1787 1788**返回值:** 1789 1790| 类型 | 说明 | 1791| ------------------- | ------------------------- | 1792| Promise<void> | 无返回结果的Promise对象。 | 1793 1794**示例:** 1795 1796```ts 1797try { 1798 let promise = preferences.flush(); 1799 promise.then(() => { 1800 console.info("Succeeded in flushing."); 1801 }).catch((err: BusinessError) => { 1802 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1803 }) 1804} catch (err) { 1805 let code = (err as BusinessError).code; 1806 let message = (err as BusinessError).message; 1807 console.error("Failed to flush. code =" + code + ", message =" + message); 1808} 1809``` 1810 1811 1812### clear 1813 1814clear(callback: AsyncCallback<void>): void 1815 1816清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 1817 1818**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1819 1820**参数:** 1821 1822| 参数名 | 类型 | 必填 | 说明 | 1823| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1824| callback | AsyncCallback<void> | 是 | 回调函数。当清除成功,err为undefined;否则为错误对象。 | 1825 1826**示例:** 1827 1828```ts 1829try { 1830 preferences.clear((err: BusinessError) =>{ 1831 if (err) { 1832 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1833 return; 1834 } 1835 console.info("Succeeded in clearing."); 1836 }) 1837} catch (err) { 1838 let code = (err as BusinessError).code; 1839 let message = (err as BusinessError).message; 1840 console.error("Failed to clear. code =" + code + ", message =" + message); 1841} 1842``` 1843 1844 1845### clear 1846 1847clear(): Promise<void> 1848 1849清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 1850 1851**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1852 1853**返回值:** 1854 1855| 类型 | 说明 | 1856| ------------------- | ------------------------- | 1857| Promise<void> | 无返回结果的Promise对象。 | 1858 1859**示例:** 1860 1861```ts 1862try { 1863 let promise = preferences.clear(); 1864 promise.then(() => { 1865 console.info("Succeeded in clearing."); 1866 }).catch((err: BusinessError) => { 1867 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1868 }) 1869} catch (err) { 1870 let code = (err as BusinessError).code; 1871 let message = (err as BusinessError).message; 1872 console.error("Failed to clear. code =" + code + ", message =" + message); 1873} 1874``` 1875 1876 1877### clearSync<sup>10+</sup> 1878 1879clearSync(): void 1880 1881清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 1882 1883**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1884 1885**示例:** 1886 1887```ts 1888try { 1889 preferences.clearSync(); 1890} catch (err) { 1891 let code = (err as BusinessError).code; 1892 let message = (err as BusinessError).message; 1893 console.error("Failed to clear. code =" + code + ", message =" + message); 1894} 1895``` 1896 1897 1898### on('change') 1899 1900on(type: 'change', callback: ( key : string ) => void): void 1901 1902订阅数据变更,订阅的Key的值发生变更后,在执行[flush](#flush)方法后,触发callback回调。 1903 1904**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1905 1906**参数:** 1907 1908| 参数名 | 类型 | 必填 | 说明 | 1909| -------- | -------- | ---- | ---------------------------------------- | 1910| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | 1911| callback | Function | 是 | 回调函数。<br />key: 发生变化的Key。 | 1912 1913**示例:** 1914 1915```ts 1916try { 1917 data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { 1918 if (err) { 1919 console.error("Failed to get preferences."); 1920 return; 1921 } 1922 preferences.on('change', (key: string) => { 1923 console.info("The key " + key + " changed."); 1924 }); 1925 preferences.put('startup', 'manual', (err: BusinessError) => { 1926 if (err) { 1927 console.error("Failed to put the value of 'startup'. Cause: " + err); 1928 return; 1929 } 1930 console.info("Succeeded in putting the value of 'startup'."); 1931 1932 preferences.flush((err: BusinessError) => { 1933 if (err) { 1934 console.error("Failed to flush. Cause: " + err); 1935 return; 1936 } 1937 console.info("Succeeded in flushing."); 1938 }) 1939 }) 1940 }) 1941} catch (err) { 1942 let code = (err as BusinessError).code; 1943 let message = (err as BusinessError).message; 1944 console.error("Failed to flush. code =" + code + ", message =" + message); 1945} 1946``` 1947 1948### on('multiProcessChange')<sup>10+</sup> 1949 1950on(type: 'multiProcessChange', callback: ( key : string ) => void): void 1951 1952订阅进程间数据变更,多个进程持有同一个首选项文件时,订阅的Key的值在任意一个进程发生变更后,执行[flush](#flush)方法后,触发callback回调。 1953 1954此方法可以配合[removePreferencesFromCache](#data_preferencesremovepreferencesfromcache)使用,当监听到有进程更新了文件时,在回调方法中更新当前的Preferences实例,如下示例2。 1955 1956**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 1957 1958**参数:** 1959 1960| 参数名 | 类型 | 必填 | 说明 | 1961| -------- | -------- | ---- | ------------------------------------------------------------ | 1962| type | string | 是 | 事件类型,固定值'multiProcessChange',表示多进程间的数据变更。 | 1963| callback | Function | 是 | 回调函数。<br />key: 发生变化的Key。 | 1964 1965**错误码:** 1966 1967以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 1968 1969| 错误码ID | 错误信息 | 1970| -------- | -------------------------------------- | 1971| 15500019 | Failed to obtain subscription service. | 1972 1973**示例1:** 1974 1975```ts 1976try { 1977 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 1978 data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { 1979 if (err) { 1980 console.error("Failed to get preferences."); 1981 return; 1982 } 1983 preferences.on('multiProcessChange', (key: string) => { 1984 console.info("The key " + key + " changed."); 1985 }); 1986 preferences.put('startup', 'manual', (err: BusinessError) => { 1987 if (err) { 1988 console.error("Failed to put the value of 'startup'. Cause: " + err); 1989 return; 1990 } 1991 console.info("Succeeded in putting the value of 'startup'."); 1992 preferences.flush((err: BusinessError) => { 1993 if (err) { 1994 console.error("Failed to flush. Cause: " + err); 1995 return; 1996 } 1997 console.info("Succeeded in flushing."); 1998 }) 1999 }) 2000 }) 2001} catch (err) { 2002 let code = (err as BusinessError).code; 2003 let message = (err as BusinessError).message; 2004 console.error("Failed to flush. code =" + code + ", message =" + message); 2005} 2006``` 2007 2008**示例2:** 2009 2010```ts 2011try { 2012 let options: data_preferences.Options = { name: 'myStore' }; 2013 data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { 2014 if (err) { 2015 console.error("Failed to get preferences."); 2016 return; 2017 } 2018 preferences = val; 2019 preferences.on('multiProcessChange', (key: string) => { 2020 console.info("The key " + key + " changed."); 2021 try { 2022 data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { 2023 if (err) { 2024 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 2025 return; 2026 } 2027 preferences = null; 2028 console.info("Succeeded in removing preferences."); 2029 }) 2030 } catch (err) { 2031 let code = (err as BusinessError).code; 2032 let message = (err as BusinessError).message; 2033 console.error("Failed to remove preferences. code =" + code + ", message =" + message); 2034 } 2035 2036 try { 2037 data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { 2038 if (err) { 2039 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 2040 return; 2041 } 2042 preferences = val; 2043 console.info("Succeeded in getting preferences."); 2044 }) 2045 } catch (err) { 2046 let code = (err as BusinessError).code; 2047 let message = (err as BusinessError).message; 2048 console.error("Failed to get preferences. code =" + code + ", message =" + message); 2049 } 2050 }); 2051 preferences.put('startup', 'manual', (err: BusinessError) => { 2052 if (err) { 2053 console.error("Failed to put the value of 'startup'. Cause: " + err); 2054 return; 2055 } 2056 console.info("Succeeded in putting the value of 'startup'."); 2057 2058 if (preferences != null) { 2059 preferences.flush((err: BusinessError) => { 2060 if (err) { 2061 console.error("Failed to flush. Cause: " + err); 2062 return; 2063 } 2064 console.info("Succeeded in flushing."); 2065 }) 2066 } 2067 }) 2068 }) 2069} catch (err) { 2070 let code = (err as BusinessError).code; 2071 let message = (err as BusinessError).message; 2072 console.error("Failed to flush. code =" + code + ", message =" + message); 2073} 2074``` 2075 2076### off('change') 2077 2078off(type: 'change', callback?: ( key : string ) => void): void 2079 2080取消订阅数据变更。 2081 2082**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2083 2084**参数:** 2085 2086| 参数名 | 类型 | 必填 | 说明 | 2087| -------- | -------- | ---- | ------------------------------------------------------------ | 2088| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | 2089| callback | Function | 否 | 需要取消的回调函数,不填写则全部取消。<br />key: 发生变化的Key。 | 2090 2091**示例:** 2092 2093```ts 2094 2095try { 2096 data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { 2097 if (err) { 2098 console.error("Failed to get preferences."); 2099 return; 2100 } 2101 preferences.on('change', (key: string) => { 2102 console.info("The key " + key + " changed."); 2103 }); 2104 preferences.put('startup', 'auto', (err: BusinessError) => { 2105 if (err) { 2106 console.error("Failed to put the value of 'startup'. Cause: " + err); 2107 return; 2108 } 2109 console.info("Succeeded in putting the value of 'startup'."); 2110 2111 preferences.flush((err: BusinessError) =>{ 2112 if (err) { 2113 console.error("Failed to flush. Cause: " + err); 2114 return; 2115 } 2116 console.info("Succeeded in flushing."); 2117 }) 2118 preferences.off('change', (key: string) => { 2119 console.info("The key " + key + " changed."); 2120 }); 2121 }) 2122 }) 2123} catch (err) { 2124 let code = (err as BusinessError).code; 2125 let message = (err as BusinessError).message; 2126 console.error("Failed to flush. code =" + code + ", message =" + message); 2127} 2128``` 2129 2130### off('multiProcessChange')<sup>10+</sup> 2131 2132off(type: 'multiProcessChange', callback?: ( key : string ) => void): void 2133 2134取消订阅进程间数据变更。 2135 2136**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2137 2138**参数:** 2139 2140| 参数名 | 类型 | 必填 | 说明 | 2141| -------- | -------- | ---- | ------------------------------------------------------------ | 2142| type | string | 是 | 事件类型,固定值'multiProcessChange',表示多进程间的数据变更。 | 2143| callback | Function | 否 | 需要取消的回调函数,不填写则全部取消。<br />key: 发生变化的Key。 | 2144 2145**示例:** 2146 2147```ts 2148try { 2149 let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; 2150 data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { 2151 if (err) { 2152 console.error("Failed to get preferences."); 2153 return; 2154 } 2155 preferences.on('multiProcessChange', (key: string) => { 2156 console.info("The key " + key + " changed."); 2157 }); 2158 preferences.put('startup', 'auto', (err: BusinessError) => { 2159 if (err) { 2160 console.error("Failed to put the value of 'startup'. Cause: " + err); 2161 return; 2162 } 2163 console.info("Succeeded in putting the value of 'startup'."); 2164 2165 preferences.flush((err: BusinessError) => { 2166 if (err) { 2167 console.error("Failed to flush. Cause: " + err); 2168 return; 2169 } 2170 console.info("Succeeded in flushing."); 2171 }) 2172 preferences.off('multiProcessChange', (key: string) => { 2173 console.info("The key " + key + " changed."); 2174 }); 2175 }) 2176 }) 2177} catch (err) { 2178 let code = (err as BusinessError).code; 2179 let message = (err as BusinessError).message; 2180 console.error("Failed to flush. code =" + code + ", message =" + message); 2181} 2182``` 2183## ValueType 2184 2185用于表示允许的数据字段类型。 2186 2187**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core 2188 2189| 类型 | 说明 | 2190| --------------- | ------------------------------ | 2191| number | 表示值类型为数字。 | 2192| string | 表示值类型为字符串。 | 2193| boolean | 表示值类型为布尔值。 | 2194| Array\<number> | 表示值类型为数字类型的数组。 | 2195| Array\<boolean> | 表示值类型为布尔类型的数组。 | 2196| Array\<string> | 表示值类型为字符串类型的数组。 | 2197