js-apis-data-preferences.md 30.4 KB
Newer Older
W
wangxiyue 已提交
1
# 首选项
P
PaDoBoo 已提交
2

3 4 5
首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。

数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。
P
PaDoBoo 已提交
6 7


P
PaDaBoo 已提交
8
> **说明:**
9
>
10
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
P
PaDoBoo 已提交
11 12 13 14


## 导入模块

15
```js
16
import data_preferences from '@ohos.data.preferences';
P
PaDoBoo 已提交
17 18
```

G
ge-yafang 已提交
19
## 常量
P
PaDoBoo 已提交
20

21
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
22

23 24 25 26
| 名称             | 参数类型 | 可读 | 可写 | 说明                                    |
| ---------------- | -------- | ---- | ---- | --------------------------------------- |
| MAX_KEY_LENGTH   | string   | 是   | 否   | Key的最大长度限制,需小于80个字节。     |
| MAX_VALUE_LENGTH | string   | 是   | 否   | Value的最大长度限制,需小于8192个字节。 |
P
PaDoBoo 已提交
27 28


29
## data_preferences.getPreferences
P
PaDoBoo 已提交
30

P
PaDaBoo 已提交
31
getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void
P
PaDoBoo 已提交
32

33
获取Preferences实例,使用callback异步回调。
P
PaDaBoo 已提交
34

P
PaDaBoo 已提交
35
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
36

G
ge-yafang 已提交
37
**参数:**
38 39 40

| 参数名   | 类型                                             | 必填 | 说明                                                         |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
41
| context  | Context            | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。                                                 |
42 43
| name     | string                                           | 是   | Preferences实例的名称。                                      |
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | 是   | 回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误码。 |
P
PaDoBoo 已提交
44

G
ge-yafang 已提交
45
**示例:**
46

47 48
FA模型示例:

49
```js
50 51 52 53
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

54
var preferences = null;
55
data_preferences.getPreferences(context, 'mystore', function (err, object) {
P
PaDaBoo 已提交
56
    if (err) {
57
        console.info("Failed to get preferences. Cause: " + err);
P
PaDaBoo 已提交
58 59
        return;
    }
60 61
    preferences = object;
    console.info("Succeeded in getting preferences.");
P
PaDaBoo 已提交
62 63
})
```
P
PaDoBoo 已提交
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context;
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

var preferences = null;
data_preferences.getPreferences(context, 'mystore', function (err, object) {
    if (err) {
        console.info("Failed to get preferences. Cause: " + err);
        return;
    }
    preferences = object;
    console.info("Succeeded in getting preferences.");
})
```
P
PaDoBoo 已提交
87

88
## data_preferences.getPreferences
P
PaDoBoo 已提交
89

P
PaDaBoo 已提交
90
getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
P
PaDoBoo 已提交
91

92
获取Preferences实例,使用Promise异步回调。
P
PaDoBoo 已提交
93

P
PaDaBoo 已提交
94
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
95

G
ge-yafang 已提交
96
**参数:**
97 98 99

| 参数名  | 类型                                  | 必填 | 说明                    |
| ------- | ------------------------------------- | ---- | ----------------------- |
100
| context | Context | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。            |
101
| name    | string                                | 是   | Preferences实例的名称。 |
P
PaDoBoo 已提交
102

G
ge-yafang 已提交
103
**返回值:**
104

105 106 107
| 类型                                       | 说明                               |
| ------------------------------------------ | ---------------------------------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise对象,返回Preferences实例。 |
P
PaDoBoo 已提交
108

G
ge-yafang 已提交
109
**示例:**
110

111 112
FA模型示例:

113
```js
114 115 116 117
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

118
var preferences = null;
119
let promise = data_preferences.getPreferences(context, 'mystore')
120 121 122
promise.then((object) => {
    preferences = object;
    console.info("Succeeded in getting preferences.");
P
PaDaBoo 已提交
123
}).catch((err) => {
124
    console.info("Failed to get preferences. Cause: " + err);
P
PaDaBoo 已提交
125 126
})
```
P
PaDoBoo 已提交
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context;
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

var preferences = null;
let promise = data_preferences.getPreferences(context, 'mystore')
promise.then((object) => {
    preferences = object;
    console.info("Succeeded in getting preferences.");
}).catch((err) => {
    console.info("Failed to get preferences. Cause: " + err);
})
```
P
PaDoBoo 已提交
149

150
## data_preferences.deletePreferences
P
PaDoBoo 已提交
151

152
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
P
PaDoBoo 已提交
153

154 155 156
从内存中移除指定的Preferences实例,使用callback异步回调。

若Preferences实例有对应的持久化文件,则同时删除其持久化文件。
157

158
调用该接口后,应用不允许再使用该Preferences实例进行数据操作,否则会出现数据一致性问题。
P
PaDoBoo 已提交
159

P
PaDaBoo 已提交
160
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
161

G
ge-yafang 已提交
162
**参数:**
163

164 165
| 参数名   | 类型                                  | 必填 | 说明                                                 |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
166
| context  | Context | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。                                         |
167
| name     | string                                | 是   | Preferences实例的名称。                              |
168
| callback | AsyncCallback&lt;void&gt;             | 是   | 回调函数。当移除成功,err为undefined,否则为错误码。 |
P
PaDoBoo 已提交
169

G
ge-yafang 已提交
170
**示例:**
171

172 173
FA模型示例:

174
```js
175 176 177 178 179
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

data_preferences.deletePreferences(context, 'mystore', function (err) {
P
PaDaBoo 已提交
180
    if (err) {
181
        console.info("Failed to delete preferences. Cause: " + err);
P
PaDaBoo 已提交
182 183
        return
    }
184
    console.info("Succeeded in deleting preferences." );
P
PaDaBoo 已提交
185 186
})
```
P
PaDoBoo 已提交
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

data_preferences.deletePreferences(context, 'mystore', function (err) {
    if (err) {
        console.info("Failed to delete preferences. Cause: " + err);
        return
    }
    console.info("Succeeded in deleting preferences." );
})
```
P
PaDoBoo 已提交
208

209
## data_preferences.deletePreferences
P
PaDoBoo 已提交
210

P
PaDaBoo 已提交
211
deletePreferences(context: Context, name: string): Promise&lt;void&gt;
P
PaDoBoo 已提交
212

213 214 215
从内存中移除指定的Preferences实例,使用Promise异步回调。

若Preferences实例有对应的持久化文件,则同时删除其持久化文件。
216

217
调用该接口后,应用不允许再使用该Preferences实例进行数据操作,否则会出现数据一致性问题。
P
PaDoBoo 已提交
218

P
PaDaBoo 已提交
219
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
220

G
ge-yafang 已提交
221
**参数:**
222 223 224

| 参数名  | 类型                                  | 必填 | 说明                    |
| ------- | ------------------------------------- | ---- | ----------------------- |
225
| context | Context | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。            |
226
| name    | string                                | 是   | Preferences实例的名称。 |
P
PaDoBoo 已提交
227

G
ge-yafang 已提交
228
**返回值:**
229

230 231 232
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
233

G
ge-yafang 已提交
234
**示例:**
235

236 237
FA模型示例:

238
```js
239 240 241 242 243
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

let promise = data_preferences.deletePreferences(context, 'mystore')
P
PaDaBoo 已提交
244
promise.then(() => {
245
    console.info("Succeeded in deleting preferences.");
P
PaDaBoo 已提交
246
}).catch((err) => {
247
    console.info("Failed to delete preferences. Cause: " + err);
P
PaDaBoo 已提交
248 249
})
```
P
PaDoBoo 已提交
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

let promise = data_preferences.deletePreferences(context, 'mystore')
promise.then(() => {
    console.info("Succeeded in deleting preferences.");
}).catch((err) => {
    console.info("Failed to delete preferences. Cause: " + err);
})
```
P
PaDoBoo 已提交
270

271
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
272

273
removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
P
PaDoBoo 已提交
274

275
从内存中移除指定的Preferences实例,使用callback异步回调。
G
ge-yafang 已提交
276

277
调用该接口后,应用不允许再使用该Preferences实例进行数据操作,否则会出现数据一致性问题。
P
PaDoBoo 已提交
278

P
PaDaBoo 已提交
279
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
280

G
ge-yafang 已提交
281
**参数:**
282

283 284
| 参数名   | 类型                                  | 必填 | 说明                                                 |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
285
| context  | Context | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。                                         |
286
| name     | string                                | 是   | Preferences实例的名称。                              |
287
| callback | AsyncCallback&lt;void&gt;             | 是   | 回调函数。当移除成功,err为undefined,否则为错误码。 |
P
PaDoBoo 已提交
288

G
ge-yafang 已提交
289
**示例:**
290

291 292
FA模型示例:

293
```js
294 295 296 297 298
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

data_preferences.removePreferencesFromCache(context, 'mystore', function (err) {
P
PaDaBoo 已提交
299
    if (err) {
300 301
        console.info("Failed to remove preferences. Cause: " + err);
        return;
P
PaDaBoo 已提交
302
    }
303
    console.info("Succeeded in removing preferences.");
P
PaDaBoo 已提交
304 305
})
```
P
PaDoBoo 已提交
306

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

data_preferences.removePreferencesFromCache(context, 'mystore', function (err) {
    if (err) {
        console.info("Failed to remove preferences. Cause: " + err);
        return;
    }
    console.info("Succeeded in removing preferences.");
})
```
P
PaDoBoo 已提交
327

328
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
329

P
PaDaBoo 已提交
330
removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
P
PaDoBoo 已提交
331

332
从内存中移除指定的Preferences实例,使用callback异步回调。
G
ge-yafang 已提交
333

334
调用该接口后,应用不允许再使用该Preferences实例进行数据操作,否则会出现数据一致性问题。
P
PaDoBoo 已提交
335

P
PaDaBoo 已提交
336
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
337

G
ge-yafang 已提交
338
**参数:**
339 340 341

| 参数名  | 类型                                  | 必填 | 说明                    |
| ------- | ------------------------------------- | ---- | ----------------------- |
342
| context | Context | 是   | 应用上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。            |
343
| name    | string                                | 是   | Preferences实例的名称。 |
P
PaDoBoo 已提交
344

G
ge-yafang 已提交
345
**返回值:**
346

347 348 349
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
350

G
ge-yafang 已提交
351
**示例:**
352

353 354
FA模型示例:

355
```js
356 357 358 359 360
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()

let promise = data_preferences.removePreferencesFromCache(context, 'mystore')
P
PaDaBoo 已提交
361
promise.then(() => {
362
    console.info("Succeeded in removing preferences.");
P
PaDaBoo 已提交
363
}).catch((err) => {
364
    console.info("Failed to remove preferences. Cause: " + err);
P
PaDaBoo 已提交
365 366
})
```
P
PaDoBoo 已提交
367

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
Stage模型示例:

```ts
// 获取context
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
        context = this.context
    }
}

let promise = data_preferences.removePreferencesFromCache(context, 'mystore')
promise.then(() => {
    console.info("Succeeded in removing preferences.");
}).catch((err) => {
    console.info("Failed to remove preferences. Cause: " + err);
})
```
P
PaDoBoo 已提交
387 388 389

## Preferences

390 391 392
存储实例,提供获取和修改存储数据的接口。

下列接口都需先使用[data_preferences.getPreferences](#data_preferencesgetpreferences)获取到Preferences实例,再通过此实例调用对应接口。
P
PaDoBoo 已提交
393 394 395 396 397 398


### get

get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void

399
获取键对应的值,如果值为null或者非默认值类型,返回默认数据,使用callback异步回调。
P
PaDoBoo 已提交
400

P
PaDaBoo 已提交
401
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
402

G
ge-yafang 已提交
403
**参数:**
404

405 406 407 408 409
| 参数名   | 类型                                         | 必填 | 说明                                                         |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| key      | string                                       | 是   | 要获取的存储Key名称,不能为空。                              |
| defValue | [ValueType](#valuetype)                      | 是   | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 |
| callback | AsyncCallback&lt;[ValueType](#valuetype)&gt; | 是   | 回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误码。 |
P
PaDoBoo 已提交
410

G
ge-yafang 已提交
411
**示例:**
412 413 414

```js
preferences.get('startup', 'default', function(err, data) {
P
PaDaBoo 已提交
415
    if (err) {
416 417
        console.info("Failed to get value of 'startup'. Cause: " + err);
        return;
P
PaDaBoo 已提交
418
    }
419
    console.info("Succeeded in getting value of 'startup'. Data: " + data);
P
PaDaBoo 已提交
420 421
})
```
P
PaDoBoo 已提交
422 423 424 425 426 427


### get

get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;

428
获取键对应的值,如果值为null或者非默认值类型,返回默认数据,使用Promise异步回调。
P
PaDoBoo 已提交
429

P
PaDaBoo 已提交
430
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
431

432
 **参数:**
433
 
434 435 436 437
| 参数名   | 类型                    | 必填 | 说明                                                         |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key      | string                  | 是   | 要获取的存储Key名称,不能为空。                              |
| defValue | [ValueType](#valuetype) | 是   | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 |
P
PaDoBoo 已提交
438

G
ge-yafang 已提交
439
**返回值:**
440 441 442 443

| 类型                                | 说明                          |
| ----------------------------------- | ----------------------------- |
| Promise<[ValueType](#valuetype)&gt; | Promise对象,返回键对应的值。 |
P
PaDoBoo 已提交
444

G
ge-yafang 已提交
445
**示例:**
446

447 448 449 450
```js
let promise = preferences.get('startup', 'default');
promise.then((data) => {
    console.info("Succeeded in getting value of 'startup'. Data: " + data);
P
PaDaBoo 已提交
451
}).catch((err) => {
452
    console.info("Failed to get value of 'startup'. Cause: " + err);
P
PaDaBoo 已提交
453 454
})
```
P
PaDoBoo 已提交
455

456 457 458 459
### getAll

getAll(callback: AsyncCallback&lt;Object&gt;): void;

460
获取含有所有键值的Object对象。
461 462 463 464

**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core

**参数:**
465

466 467 468
| 参数名   | 类型                        | 必填 | 说明                                                         |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;Object&gt; | 是   | 回调函数。当获取成功,err为undefined,value为含有所有键值的Object对象;否则err为错误码。 |
469 470

**示例:**
471 472

```js
L
li_juntao 已提交
473
preferences.getAll(function (err, value) {
474
    if (err) {
475 476
        console.info("Failed to get all key-values. Cause: " + err);
        return;
477
    }
478 479
    let allKeys = Object.keys(value);
    console.info("getAll keys = " + allKeys);
480
    console.info("getAll object = " + JSON.stringify(value));
481 482 483 484 485 486 487 488
});
```


### getAll

getAll(): Promise&lt;Object&gt;

489
获取含有所有键值的Object对象。
490 491 492 493

**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core

**返回值:**
494

495 496 497
| 类型                  | 说明                                        |
| --------------------- | ------------------------------------------- |
| Promise&lt;Object&gt; | Promise对象,返回含有所有键值的Object对象。 |
498 499

**示例:**
500

501 502
```js
let promise = preferences.getAll();
503
promise.then((value) => {
504 505
    let allKeys = Object.keys(value);
    console.info('getAll keys = ' + allKeys);
506
    console.info("getAll object = " + JSON.stringify(value));
507
}).catch((err) => {
508
    console.info("Failed to get all key-values. Cause: " + err);
509 510
})
```
P
PaDoBoo 已提交
511 512 513 514 515

### put

put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void

516
将数据写入Preferences实例,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。
P
PaDoBoo 已提交
517

P
PaDaBoo 已提交
518
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
519

G
ge-yafang 已提交
520
**参数:**
521

522 523 524 525 526
| 参数名   | 类型                      | 必填 | 说明                                                         |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| key      | string                    | 是   | 要修改的存储的Key,不能为空。                                |
| value    | [ValueType](#valuetype)   | 是   | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 |
| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。当数据写入成功,err为undefined;否则为错误码。     |
P
PaDoBoo 已提交
527

G
ge-yafang 已提交
528
**示例:**
529

530
```js
531
preferences.put('startup', 'auto', function (err) {
P
PaDaBoo 已提交
532
    if (err) {
533 534
        console.info("Failed to put value of 'startup'. Cause: " + err);
        return;
P
PaDaBoo 已提交
535
    }
536
    console.info("Succeeded in putting value of 'startup'.");
P
PaDaBoo 已提交
537 538
})
```
P
PaDoBoo 已提交
539 540 541 542 543 544


### put

put(key: string, value: ValueType): Promise&lt;void&gt;

545
将数据写入Preferences实例,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。
P
PaDoBoo 已提交
546

P
PaDaBoo 已提交
547
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
548

G
ge-yafang 已提交
549
**参数:**
550

551 552 553 554
| 参数名 | 类型                    | 必填 | 说明                                                         |
| ------ | ----------------------- | ---- | ------------------------------------------------------------ |
| key    | string                  | 是   | 要修改的存储的Key,不能为空。                                |
| value  | [ValueType](#valuetype) | 是   | 存储的新值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 |
P
PaDoBoo 已提交
555

G
ge-yafang 已提交
556
**返回值:**
557

558 559 560
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
561

G
ge-yafang 已提交
562
**示例:**
563

564 565
```js
let promise = preferences.put('startup', 'auto');
P
PaDaBoo 已提交
566
promise.then(() => {
567
    console.info("Succeeded in putting value of 'startup'.");
P
PaDaBoo 已提交
568
}).catch((err) => {
569
    console.info("Failed to put value of 'startup'. Cause: " + err);
P
PaDaBoo 已提交
570 571
})
```
P
PaDoBoo 已提交
572 573 574 575


### has

576
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
P
PaDoBoo 已提交
577

578
检查Preferences实例是否包含名为给定Key的存储键值对,使用callback异步回调。
P
PaDoBoo 已提交
579

P
PaDaBoo 已提交
580
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
581

G
ge-yafang 已提交
582
**参数:**
583

584 585 586
| 参数名   | 类型                         | 必填 | 说明                                                         |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
| key      | string                       | 是   | 要检查的存储key名称,不能为空。                              |
587
| callback | AsyncCallback&lt;boolean&gt; | 是   | 回调函数。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 |
P
PaDoBoo 已提交
588

G
ge-yafang 已提交
589
**示例:**
590

591
```js
592
preferences.has('startup', function (err, isExist) {
P
PaDaBoo 已提交
593
    if (err) {
594
        console.info("Failed to check the key 'startup'. Cause: " + err);
595
        return;
P
PaDaBoo 已提交
596 597
    }
    if (isExist) {
598
        console.info("The key 'startup' is contained.");
P
PaDaBoo 已提交
599
    } else {
600
        console.info("The key 'startup' dose not contain.");
P
PaDaBoo 已提交
601 602 603
    }
})
```
P
PaDoBoo 已提交
604 605 606 607 608 609


### has

has(key: string): Promise&lt;boolean&gt;

610
检查Preferences实例是否包含名为给定Key的存储键值对,使用Promise异步回调。
P
PaDoBoo 已提交
611

P
PaDaBoo 已提交
612
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
613

G
ge-yafang 已提交
614
**参数:**
615

616 617 618
| 参数名 | 类型   | 必填 | 说明                            |
| ------ | ------ | ---- | ------------------------------- |
| key    | string | 是   | 要检查的存储key名称,不能为空。 |
P
PaDoBoo 已提交
619

G
ge-yafang 已提交
620
**返回值:**
621

622 623
| 类型                   | 说明                                                         |
| ---------------------- | ------------------------------------------------------------ |
624
| Promise&lt;boolean&gt; | Promise对象。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 |
P
PaDoBoo 已提交
625

G
ge-yafang 已提交
626
**示例:**
627 628 629

```js
let promise = preferences.has('startup');
P
PaDaBoo 已提交
630 631
promise.then((isExist) => {
    if (isExist) {
632
        console.info("The key 'startup' is contained.");
P
PaDaBoo 已提交
633
    } else {
634
        console.info("The key 'startup' dose not contain.");
P
PaDaBoo 已提交
635 636
    }
}).catch((err) => {
637
    console.info("Failed to check the key 'startup'. Cause: " + err);
P
PaDaBoo 已提交
638 639
})
```
P
PaDoBoo 已提交
640 641 642 643 644 645


### delete

delete(key: string, callback: AsyncCallback&lt;void&gt;): void

646
从Preferences实例中删除名为给定Key的存储键值对,使用callback异步回调。
P
PaDoBoo 已提交
647

P
PaDaBoo 已提交
648
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
649

G
ge-yafang 已提交
650
**参数:**
651

652 653 654 655
| 参数名   | 类型                      | 必填 | 说明                                                 |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| key      | string                    | 是   | 要删除的存储Key名称,不能为空。                      |
| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。当删除成功,err为undefined;否则为错误码。 |
P
PaDoBoo 已提交
656

G
ge-yafang 已提交
657
**示例:**
658

659
```js
660
preferences.delete('startup', function (err) {
P
PaDaBoo 已提交
661
    if (err) {
662 663
        console.info("Failed to delete the key 'startup'. Cause: " + err);
        return;
P
PaDaBoo 已提交
664
    }
665
    console.info("Succeeded in deleting the key 'startup'.");
P
PaDaBoo 已提交
666 667
})
```
P
PaDoBoo 已提交
668 669 670 671 672 673


### delete

delete(key: string): Promise&lt;void&gt;

674
从Preferences实例中删除名为给定Key的存储键值对,使用Promise异步回调。
P
PaDoBoo 已提交
675

P
PaDaBoo 已提交
676
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
677

G
ge-yafang 已提交
678
**参数:**
679

680 681 682
| 参数名 | 类型   | 必填 | 说明                            |
| ------ | ------ | ---- | ------------------------------- |
| key    | string | 是   | 要删除的存储key名称,不能为空。 |
P
PaDoBoo 已提交
683

G
ge-yafang 已提交
684
**返回值:**
685

686 687 688
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
689

G
ge-yafang 已提交
690
**示例:**
691

692 693
```js
let promise = preferences.delete('startup');
P
PaDaBoo 已提交
694
promise.then(() => {
695
    console.info("Succeeded in deleting the key 'startup'.");
P
PaDaBoo 已提交
696
}).catch((err) => {
697
    console.info("Failed to delete the key 'startup'. Cause: " + err);
P
PaDaBoo 已提交
698 699
})
```
P
PaDoBoo 已提交
700 701 702 703 704 705


### flush

flush(callback: AsyncCallback&lt;void&gt;): void

706
将当前Preferences实例的数据异步存储到首选项持久化文件中,使用callback异步回调。
P
PaDoBoo 已提交
707

P
PaDaBoo 已提交
708
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
709

G
ge-yafang 已提交
710
**参数:**
711

712 713 714
| 参数名   | 类型                      | 必填 | 说明                                                 |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。当保存成功,err为undefined;否则为错误码。 |
P
PaDoBoo 已提交
715

G
ge-yafang 已提交
716
**示例:**
717

718
```js
719
preferences.flush(function (err) {
P
PaDaBoo 已提交
720
    if (err) {
721 722
        console.info("Failed to flush. Cause: " + err);
        return;
P
PaDaBoo 已提交
723
    }
724
    console.info("Succeeded in flushing.");
P
PaDaBoo 已提交
725 726
})
```
P
PaDoBoo 已提交
727 728 729 730 731 732


### flush

flush(): Promise&lt;void&gt;

733
将当前Preferences实例的数据异步存储到首选项持久化文件中,使用Promise异步回调。
P
PaDoBoo 已提交
734

P
PaDaBoo 已提交
735
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
736

G
ge-yafang 已提交
737
**返回值:**
738

739 740 741
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
742

G
ge-yafang 已提交
743
**示例:**
744

745 746
```js
let promise = preferences.flush();
P
PaDaBoo 已提交
747
promise.then(() => {
748
    console.info("Succeeded in flushing.");
P
PaDaBoo 已提交
749
}).catch((err) => {
750
    console.info("Failed to flush. Cause: " + err);
P
PaDaBoo 已提交
751 752
})
```
P
PaDoBoo 已提交
753 754 755 756 757 758


### clear

clear(callback: AsyncCallback&lt;void&gt;): void

759
清除此Preferences实例中的所有存储,使用callback异步回调。
P
PaDoBoo 已提交
760

P
PaDaBoo 已提交
761
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
762

G
ge-yafang 已提交
763
**参数:**
764

765 766 767
| 参数名   | 类型                      | 必填 | 说明                                                 |
| -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。当清除成功,err为undefined;否则为错误码。 |
P
PaDoBoo 已提交
768

G
ge-yafang 已提交
769
**示例:**
770

771
```js
772
preferences.clear(function (err) {
P
PaDaBoo 已提交
773
    if (err) {
774 775
        console.info("Failed to clear. Cause: " + err);
        return;
P
PaDaBoo 已提交
776
    }
777
    console.info("Succeeded in clearing.");
P
PaDaBoo 已提交
778 779
})
```
P
PaDoBoo 已提交
780 781 782 783 784 785


### clear

clear(): Promise&lt;void&gt;

786
清除此Preferences实例中的所有存储,使用Promise异步回调。
P
PaDoBoo 已提交
787

P
PaDaBoo 已提交
788
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
789

G
ge-yafang 已提交
790
**返回值:**
791

792 793 794
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
795

G
ge-yafang 已提交
796
**示例:**
797

798
```js
799
let promise = preferences.clear()
P
PaDaBoo 已提交
800
promise.then(() => {
801
    console.info("Succeeded in clearing.");
P
PaDaBoo 已提交
802
}).catch((err) => {
803
    console.info("Failed to clear. Cause: " + err);
P
PaDaBoo 已提交
804 805
})
```
P
PaDoBoo 已提交
806 807 808 809 810 811


### on('change')

on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void

812
订阅数据变更,订阅的Key的值发生变更后,在执行[flush](#flush)方法后,触发callback回调。
P
PaDoBoo 已提交
813

P
PaDaBoo 已提交
814
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
815

G
ge-yafang 已提交
816
**参数:**
817

818 819 820 821
| 参数名   | 类型                             | 必填 | 说明                                     |
| -------- | -------------------------------- | ---- | ---------------------------------------- |
| type     | string                           | 是   | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;{ key : string }&gt; | 是   | 回调对象实例。                           |
P
PaDoBoo 已提交
822

G
ge-yafang 已提交
823
**示例:**
824

825
```js
L
li_juntao 已提交
826
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
P
PaDaBoo 已提交
827
    if (err) {
828
        console.info("Failed to get preferences.");
L
li_juntao 已提交
829
        return;
P
PaDaBoo 已提交
830
    }
L
li_juntao 已提交
831
    var observer = function (key) {
832
        console.info("The key " + key + " changed.");
L
li_juntao 已提交
833
    }
834
    preferences.on('change', observer);
L
li_juntao 已提交
835
    preferences.put('startup', 'auto', function (err) {
P
PaDaBoo 已提交
836
        if (err) {
837 838
            console.info("Failed to put the value of 'startup'. Cause: " + err);
            return;
P
PaDaBoo 已提交
839
        }
840
        console.info("Succeeded in putting the value of 'startup'.");
L
li_juntao 已提交
841 842 843

        preferences.flush(function (err) {
            if (err) {
844 845
                console.info("Failed to flush. Cause: " + err);
                return;
L
li_juntao 已提交
846
            }
847
            console.info("Succeeded in flushing."); // observer will be called.
L
li_juntao 已提交
848
        })
P
PaDaBoo 已提交
849 850 851
    })
})
```
P
PaDoBoo 已提交
852 853 854 855


### off('change')

856
off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void
P
PaDoBoo 已提交
857

858
取消订阅数据变更。
P
PaDoBoo 已提交
859

P
PaDaBoo 已提交
860
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
861

G
ge-yafang 已提交
862
**参数:**
863

864 865 866 867
| 参数名   | 类型                             | 必填 | 说明                                       |
| -------- | -------------------------------- | ---- | ------------------------------------------ |
| type     | string                           | 是   | 事件类型,固定值'change',表示数据变更。   |
| callback | Callback&lt;{ key : string }&gt; | 否   | 需要取消的回调对象实例,不填写则全部取消。 |
P
PaDoBoo 已提交
868

G
ge-yafang 已提交
869
**示例:**
870

871
```js
L
li_juntao 已提交
872
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
P
PaDaBoo 已提交
873
    if (err) {
874
        console.info("Failed to get preferences.");
L
li_juntao 已提交
875
        return;
P
PaDaBoo 已提交
876
    }
L
li_juntao 已提交
877
    var observer = function (key) {
878
        console.info("The key " + key + " changed.");
L
li_juntao 已提交
879
    }
880
    preferences.on('change', observer);
L
li_juntao 已提交
881
    preferences.put('startup', 'auto', function (err) {
P
PaDaBoo 已提交
882
        if (err) {
883 884
            console.info("Failed to put the value of 'startup'. Cause: " + err);
            return;
P
PaDaBoo 已提交
885
        }
886
        console.info("Succeeded in putting the value of 'startup'.");
L
li_juntao 已提交
887 888 889

        preferences.flush(function (err) {
            if (err) {
890 891
                console.info("Failed to flush. Cause: " + err);
                return;
L
li_juntao 已提交
892
            }
893
            console.info("Succeeded in flushing."); // observer will be called.
L
li_juntao 已提交
894
        })
895
        preferences.off('change', observer);
P
PaDaBoo 已提交
896 897 898
    })
})
```
G
ge-yafang 已提交
899 900 901 902 903

## ValueType

用于表示允许的数据字段类型。

P
PaDaBoo 已提交
904
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
G
ge-yafang 已提交
905

906 907 908 909 910
| 类型            | 说明                           |
| --------------- | ------------------------------ |
| number          | 表示值类型为数字。             |
| string          | 表示值类型为字符串。           |
| boolean         | 表示值类型为布尔值。           |
911 912
| Array\<number>  | 表示值类型为数字类型的数组。   |
| Array\<boolean> | 表示值类型为布尔类型的数组。   |
913
| Array\<string>  | 表示值类型为字符串类型的数组。 |