js-apis-data-preferences.md 36.0 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
// 获取context
51 52 53
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
let preferences = null;
D
duanweiling 已提交
54

D
duanweiling 已提交
55
try {
D
duanweiling 已提交
56 57
    data_preferences.getPreferences(context, 'mystore', function (err, val) {
        if (err) {
D
duanweiling 已提交
58 59 60 61 62
	        console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
	        return;
	    }
	    console.info("Succeeded in getting preferences.");
	})
D
duanweiling 已提交
63
} catch (err) {
D
duanweiling 已提交
64
	console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
65
}
P
PaDaBoo 已提交
66
```
P
PaDoBoo 已提交
67

68 69 70 71
Stage模型示例:

```ts
// 获取context
72 73
import Ability from '@ohos.application.Ability';
let context = null;
74 75
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
76
        context = this.context;
77 78 79
    }
}

80
let preferences = null;
D
duanweiling 已提交
81
try {
D
duanweiling 已提交
82 83 84 85 86 87 88
	data_preferences.getPreferences(context, 'mystore', function (err, val) {
	    if (err) {
	        console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
	        return;
	    }
	    console.info("Succeeded in getting preferences.");
	})
D
duanweiling 已提交
89
} catch (err) {
D
duanweiling 已提交
90
	console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
91
}
92
```
P
PaDoBoo 已提交
93

94
## data_preferences.getPreferences
P
PaDoBoo 已提交
95

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

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

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

G
ge-yafang 已提交
102
**参数:**
103 104 105

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

G
ge-yafang 已提交
109
**返回值:**
110

111 112 113
| 类型                                       | 说明                               |
| ------------------------------------------ | ---------------------------------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise对象,返回Preferences实例。 |
P
PaDoBoo 已提交
114

G
ge-yafang 已提交
115
**示例:**
116

117 118
FA模型示例:

119
```js
120
// 获取context
121 122
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
123

D
duanweiling 已提交
124
let preferences = null;
D
duanweiling 已提交
125
try{
D
duanweiling 已提交
126 127 128 129
    let promise = data_preferences.getPreferences(context, 'mystore');
    promise.then((object) => {
    preferences = object;
    console.info("Succeeded in getting preferences.");
D
duanweiling 已提交
130
    }).catch((err) => {
D
duanweiling 已提交
131
        console.log("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
132 133
    })
} catch(err) {
D
duanweiling 已提交
134
    console.log("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
135
}
P
PaDaBoo 已提交
136
```
P
PaDoBoo 已提交
137

138 139 140 141
Stage模型示例:

```ts
// 获取context
142 143
import Ability from '@ohos.application.Ability';
let context = null;
144 145
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
146
        context = this.context;
147 148 149
    }
}

D
duanweiling 已提交
150
let preferences = null;
D
duanweiling 已提交
151
try{
D
duanweiling 已提交
152 153 154 155
    let promise = data_preferences.getPreferences(context, 'mystore');
    promise.then((object) => {
    preferences = object;
    console.info("Succeeded in getting preferences.");
D
duanweiling 已提交
156
    }).catch((err) => {
D
duanweiling 已提交
157
    console.log("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
158 159
    })
} catch(err) {
D
duanweiling 已提交
160
    console.log("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
161
}
162
```
P
PaDoBoo 已提交
163

164
## data_preferences.deletePreferences
P
PaDoBoo 已提交
165

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

168 169 170
从内存中移除指定的Preferences实例,使用callback异步回调。

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

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

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

G
ge-yafang 已提交
176
**参数:**
177

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

D
duanweiling 已提交
184 185 186 187 188 189 190 191
**错误码:**

以下错误码的详细介绍请参见[首选项错误码](../errorcodes/errorcode-preferences.md)

| 错误码ID | 错误信息                       |
| -------- | ------------------------------|
| 15500010 | Failed to delete preferences. |

G
ge-yafang 已提交
192
**示例:**
193

194 195
FA模型示例:

196
```js
197
// 获取context
198 199
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
200

D
duanweiling 已提交
201
try {
D
duanweiling 已提交
202
    data_preferences.deletePreferences(context, 'mystore', function (err, val) {
D
duanweiling 已提交
203
        if (err) {
D
duanweiling 已提交
204 205
            console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
206
        }
D
duanweiling 已提交
207
        console.info("Succeeded in deleting preferences." );
D
duanweiling 已提交
208 209
    })
} catch (err) {
D
duanweiling 已提交
210
    console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
211
}
P
PaDaBoo 已提交
212
```
P
PaDoBoo 已提交
213

214 215 216 217
Stage模型示例:

```ts
// 获取context
218 219
import Ability from '@ohos.application.Ability';
let context = null;
220 221
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
222
        context = this.context;
223 224 225
    }
}

D
duanweiling 已提交
226
try {
D
duanweiling 已提交
227
    data_preferences.deletePreferences(context, 'mystore', function (err, val) {
D
duanweiling 已提交
228
        if (err) {
D
duanweiling 已提交
229 230
            console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
231
        }
D
duanweiling 已提交
232
        console.info("Succeeded in deleting preferences." );
D
duanweiling 已提交
233 234
    })
} catch (err) {
D
duanweiling 已提交
235
    console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
236
}
237
```
P
PaDoBoo 已提交
238

239
## data_preferences.deletePreferences
P
PaDoBoo 已提交
240

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

243 244 245
从内存中移除指定的Preferences实例,使用Promise异步回调。

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

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

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

G
ge-yafang 已提交
251
**参数:**
252 253 254

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

D
duanweiling 已提交
258 259 260 261 262 263
**返回值:**

| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |

D
duanweiling 已提交
264 265 266 267 268 269 270 271
**错误码:**

以下错误码的详细介绍请参见[首选项错误码](../errorcodes/errorcode-preferences.md)

| 错误码ID | 错误信息                       |
| -------- | ------------------------------|
| 15500010 | Failed to delete preferences. |

G
ge-yafang 已提交
272
**示例:**
273

274 275
FA模型示例:

276
```js
277
// 获取context
278 279
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
280

D
duanweiling 已提交
281
try{
D
duanweiling 已提交
282 283 284
    let promise = data_preferences.deletePreferences(context, 'mystore');
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
D
duanweiling 已提交
285
    }).catch((err) => {
D
duanweiling 已提交
286
       console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
287 288
    })
} catch(err) {
D
duanweiling 已提交
289
    console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
290
}
P
PaDaBoo 已提交
291
```
P
PaDoBoo 已提交
292

293 294 295 296
Stage模型示例:

```ts
// 获取context
297 298
import Ability from '@ohos.application.Ability';
let context = null;
299 300
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
301
        context = this.context;
302 303 304
    }
}

D
duanweiling 已提交
305
try{
D
duanweiling 已提交
306 307 308
    let promise = data_preferences.deletePreferences(context, 'mystore');
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
D
duanweiling 已提交
309
    }).catch((err) => {
D
duanweiling 已提交
310
       console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
311 312
    })
} catch(err) {
D
duanweiling 已提交
313
         console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
314
}
315
```
P
PaDoBoo 已提交
316

317
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
318

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

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

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

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

G
ge-yafang 已提交
327
**参数:**
328

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

G
ge-yafang 已提交
335
**示例:**
336

337 338
FA模型示例:

339
```js
340
// 获取context
341 342
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
343

D
duanweiling 已提交
344
try {
D
duanweiling 已提交
345
    data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
D
duanweiling 已提交
346
        if (err) {
D
duanweiling 已提交
347 348
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
349
        }
D
duanweiling 已提交
350 351 352
        expect(true).assertEqual(val);
        console.info("Succeeded in removing preferences.");
    })
D
duanweiling 已提交
353
} catch (err) {
D
duanweiling 已提交
354
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
355
}
P
PaDaBoo 已提交
356
```
P
PaDoBoo 已提交
357

358 359 360 361
Stage模型示例:

```ts
// 获取context
362 363
import Ability from '@ohos.application.Ability';
let context = null;
364 365
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
366
        context = this.context;
367 368 369
    }
}

D
duanweiling 已提交
370
try {
D
duanweiling 已提交
371
    data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
D
duanweiling 已提交
372
        if (err) {
D
duanweiling 已提交
373 374
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
375
        }
D
duanweiling 已提交
376 377 378
        expect(true).assertEqual(val);
        console.info("Succeeded in removing preferences.");
    })
D
duanweiling 已提交
379
} catch (err) {
D
duanweiling 已提交
380
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
381
}
D
duanweiling 已提交
382

383
```
P
PaDoBoo 已提交
384

385
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
386

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

A
Annie_wang 已提交
389
从内存中移除指定的Preferences实例,使用Promise异步回调。
G
ge-yafang 已提交
390

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

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

G
ge-yafang 已提交
395
**参数:**
396 397 398

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

G
ge-yafang 已提交
402
**返回值:**
403

404 405 406
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
407

G
ge-yafang 已提交
408
**示例:**
409

410 411
FA模型示例:

412
```js
413
// 获取context
414 415
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
416

D
duanweiling 已提交
417
try{
D
duanweiling 已提交
418 419 420
    let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
	promise.then(() => {
    	console.info("Succeeded in removing preferences.");
D
duanweiling 已提交
421
    }).catch((err) => {
D
duanweiling 已提交
422
        console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
423 424
    })
} catch(err) {
D
duanweiling 已提交
425
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
426
}
P
PaDaBoo 已提交
427
```
P
PaDoBoo 已提交
428

429 430 431 432
Stage模型示例:

```ts
// 获取context
433 434
import Ability from '@ohos.application.Ability';
let context = null;
435 436
class MainAbility extends Ability{
    onWindowStageCreate(windowStage){
437
        context = this.context;
438 439 440
    }
}

D
duanweiling 已提交
441
try{
D
duanweiling 已提交
442 443 444
    let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
	promise.then(() => {
    	console.info("Succeeded in removing preferences.");
D
duanweiling 已提交
445
    }).catch((err) => {
D
duanweiling 已提交
446
        console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
447 448
    })
} catch(err) {
D
duanweiling 已提交
449
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
450
}
451
```
P
PaDoBoo 已提交
452 453 454

## Preferences

455 456 457
存储实例,提供获取和修改存储数据的接口。

下列接口都需先使用[data_preferences.getPreferences](#data_preferencesgetpreferences)获取到Preferences实例,再通过此实例调用对应接口。
P
PaDoBoo 已提交
458 459 460 461 462 463


### get

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

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

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

G
ge-yafang 已提交
468
**参数:**
469

470 471 472 473 474
| 参数名   | 类型                                         | 必填 | 说明                                                         |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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 已提交
475

G
ge-yafang 已提交
476
**示例:**
477 478

```js
D
duanweiling 已提交
479
try {
D
duanweiling 已提交
480
    data_preferences.get('startup', 'default', function (err, val) {
D
duanweiling 已提交
481
        if (err) {
D
duanweiling 已提交
482 483
            console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
484
        }
D
duanweiling 已提交
485 486
        expect(true).assertEqual(val);
        console.info("Succeeded in getting value of 'startup'. val: " + val);
D
duanweiling 已提交
487 488
    })
} catch (err) {
D
duanweiling 已提交
489
    console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
490
}
P
PaDaBoo 已提交
491
```
P
PaDoBoo 已提交
492 493 494 495 496 497


### get

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

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

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

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

G
ge-yafang 已提交
509
**返回值:**
510 511 512 513

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

G
ge-yafang 已提交
515
**示例:**
516

517
```js
D
duanweiling 已提交
518
try{
D
duanweiling 已提交
519 520 521
    let promise = preferences.get('startup', 'default');
    promise.then((data) => {
        console.info("Succeeded in getting value of 'startup'. Data: " + data);
D
duanweiling 已提交
522
    }).catch((err) => {
D
duanweiling 已提交
523
        console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
524 525
    })
} catch(err) {
D
duanweiling 已提交
526
    console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
527
}
P
PaDaBoo 已提交
528
```
P
PaDoBoo 已提交
529

530 531 532 533
### getAll

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

534
获取含有所有键值的Object对象。
535 536 537 538

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

**参数:**
539

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

**示例:**
545 546

```js
D
duanweiling 已提交
547
try {
D
duanweiling 已提交
548
    preferences.getAll(function (err, value) {
D
duanweiling 已提交
549
        if (err) {
D
duanweiling 已提交
550 551
            console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
552
        }
D
duanweiling 已提交
553 554 555
    let allKeys = Object.keys(value);
    console.info("getAll keys = " + allKeys);
    console.info("getAll object = " + JSON.stringify(value));
D
duanweiling 已提交
556 557
    })
} catch (err) {
D
duanweiling 已提交
558
 console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
559
}
560 561 562 563 564 565 566
```


### getAll

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

567
获取含有所有键值的Object对象。
568 569 570 571

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

**返回值:**
572

573 574 575
| 类型                  | 说明                                        |
| --------------------- | ------------------------------------------- |
| Promise&lt;Object&gt; | Promise对象,返回含有所有键值的Object对象。 |
576 577

**示例:**
578

579
```js
D
duanweiling 已提交
580
try {
D
duanweiling 已提交
581 582
    let promise = preferences.getAll();
    promise.then((value) => {
D
duanweiling 已提交
583 584 585
    let allKeys = Object.keys(value);
    console.info('getAll keys = ' + allKeys);
    console.info("getAll object = " + JSON.stringify(value));
D
duanweiling 已提交
586
    }).catch((err) => {
D
duanweiling 已提交
587
         console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
588 589
    })
} catch (err) {
D
duanweiling 已提交
590
    console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
591
}
592
```
P
PaDoBoo 已提交
593 594 595 596 597

### put

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

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

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

G
ge-yafang 已提交
602
**参数:**
603

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

G
ge-yafang 已提交
610
**示例:**
611

612
```js
D
duanweiling 已提交
613
try{
D
duanweiling 已提交
614
    preferences.put('startup', 'auto', function (err) {
D
duanweiling 已提交
615
        if (err) {
D
duanweiling 已提交
616
            console.info("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
617
            return;
D
duanweiling 已提交
618
        }
D
duanweiling 已提交
619
    console.info("Succeeded in putting value of 'startup'.");
D
duanweiling 已提交
620
    })
D
duanweiling 已提交
621
} catch (err) {
D
duanweiling 已提交
622
    console.info("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
623
}
P
PaDaBoo 已提交
624
```
P
PaDoBoo 已提交
625 626 627 628 629 630


### put

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

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

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

G
ge-yafang 已提交
635
**参数:**
636

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

G
ge-yafang 已提交
642
**返回值:**
643

644 645 646
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
647

G
ge-yafang 已提交
648
**示例:**
649

650
```js
D
duanweiling 已提交
651
try{
D
duanweiling 已提交
652
    let promise = preferences.put('startup', 'auto');
D
duanweiling 已提交
653
    promise.then(() => {
D
duanweiling 已提交
654
    console.info("Succeeded in putting value of 'startup'.");
D
duanweiling 已提交
655
    }).catch((err) => {
D
duanweiling 已提交
656
        console.info("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
657 658
    })
} catch(err) {
D
duanweiling 已提交
659
    console.info("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
660
}
P
PaDaBoo 已提交
661
```
P
PaDoBoo 已提交
662 663 664 665


### has

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

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

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

G
ge-yafang 已提交
672
**参数:**
673

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

G
ge-yafang 已提交
679
**示例:**
680

681
```js
D
duanweiling 已提交
682 683 684 685 686 687 688 689 690 691 692 693
try{
    preferences.has('startup', function (err, val) {
    if (err) {
      console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
      return;
    }
    if (val) {
      console.info("The key 'startup' is contained.");
    } else {
      console.info("The key 'startup' dose not contain.");
    }
  })
D
duanweiling 已提交
694 695
} catch (err) {
    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
696
}
P
PaDaBoo 已提交
697
```
P
PaDoBoo 已提交
698 699 700 701 702 703


### has

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

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

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

G
ge-yafang 已提交
708
**参数:**
709

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

G
ge-yafang 已提交
714
**返回值:**
715

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

G
ge-yafang 已提交
720
**示例:**
721 722

```js
D
duanweiling 已提交
723 724 725
try{
    let promise = preferences.has('startup');
    promise.then((val) => {
D
duanweiling 已提交
726 727 728 729 730
        if (val) {
          console.info("The key 'startup' is contained.");
        } else {
          console.info("The key 'startup' dose not contain.");
        }
D
duanweiling 已提交
731
    }).catch((err) => {
D
duanweiling 已提交
732
        console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
733 734 735 736
  })
} catch(err) {
  console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
P
PaDaBoo 已提交
737
```
P
PaDoBoo 已提交
738 739 740 741 742 743


### delete

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

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

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

G
ge-yafang 已提交
748
**参数:**
749

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

G
ge-yafang 已提交
755
**示例:**
756

757
```js
D
duanweiling 已提交
758
try{
D
duanweiling 已提交
759
    preferences.delete('startup', function (err) {
D
duanweiling 已提交
760
        if (err) {
D
duanweiling 已提交
761 762
            console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
763
        }
D
duanweiling 已提交
764
    console.info("Succeeded in deleting the key 'startup'.");
D
duanweiling 已提交
765
    })
D
duanweiling 已提交
766 767
} catch (err) {
    console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
768
}
P
PaDaBoo 已提交
769
```
P
PaDoBoo 已提交
770 771 772 773 774 775


### delete

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

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

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

G
ge-yafang 已提交
780
**参数:**
781

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

G
ge-yafang 已提交
786
**返回值:**
787

788 789 790
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
791

G
ge-yafang 已提交
792
**示例:**
793

794
```js
D
duanweiling 已提交
795
try{
D
duanweiling 已提交
796
    let promise = preferences.delete('startup');
D
duanweiling 已提交
797 798
	promise.then(() => {
    	console.info("Succeeded in deleting the key 'startup'.");
D
duanweiling 已提交
799
    }).catch((err) => {
D
duanweiling 已提交
800
        console.log("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
801 802
    })
} catch(err) {
D
duanweiling 已提交
803
    console.log("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
804
}
P
PaDaBoo 已提交
805
```
P
PaDoBoo 已提交
806 807 808 809 810 811


### flush

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

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

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

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

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

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

824
```js
D
duanweiling 已提交
825
try{
D
duanweiling 已提交
826 827 828 829
    preferences.flush(function (err) {
         if (err) {
            console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
830
        }
D
duanweiling 已提交
831
         console.info("Succeeded in flushing.");
D
duanweiling 已提交
832
    })
D
duanweiling 已提交
833 834
} catch (err) {
    console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
835
}
P
PaDaBoo 已提交
836
```
P
PaDoBoo 已提交
837 838 839 840 841 842


### flush

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

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

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

G
ge-yafang 已提交
847
**返回值:**
848

849 850 851
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
852

G
ge-yafang 已提交
853
**示例:**
854

855
```js
D
duanweiling 已提交
856
try {
D
duanweiling 已提交
857
    let promise = preferences.flush();
D
duanweiling 已提交
858
    promise.then(() => {
D
duanweiling 已提交
859
    console.info("Succeeded in flushing.");
D
duanweiling 已提交
860
    }).catch((err) => {
D
duanweiling 已提交
861
        console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
862 863
    })
} catch (err) {
D
duanweiling 已提交
864
   console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
865
}
P
PaDaBoo 已提交
866
```
P
PaDoBoo 已提交
867 868 869 870 871 872


### clear

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

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

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

G
ge-yafang 已提交
877
**参数:**
878

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

G
ge-yafang 已提交
883
**示例:**
884

885
```js
D
duanweiling 已提交
886
try{
D
duanweiling 已提交
887 888 889 890
preferences.clear(function (err) {
    if (err) {
            console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
891
        }
D
duanweiling 已提交
892
          console.info("Succeeded in clearing.");
D
duanweiling 已提交
893
    })
D
duanweiling 已提交
894 895
} catch (err) {
     console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
896
}
P
PaDaBoo 已提交
897
```
P
PaDoBoo 已提交
898 899 900 901 902 903


### clear

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

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

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

G
ge-yafang 已提交
908
**返回值:**
909

910 911 912
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
913

G
ge-yafang 已提交
914
**示例:**
915

916
```js
D
duanweiling 已提交
917
try{
D
duanweiling 已提交
918
    let promise = preferences.clear()
D
duanweiling 已提交
919 920
	promise.then(() => {
    	console.info("Succeeded in clearing.");
D
duanweiling 已提交
921
    }).catch((err) => {
D
duanweiling 已提交
922
       console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
923 924
    })
} catch(err) {
D
duanweiling 已提交
925
    console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
926
}
P
PaDaBoo 已提交
927
```
P
PaDoBoo 已提交
928 929 930 931 932 933


### on('change')

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

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

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

G
ge-yafang 已提交
938
**参数:**
939

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

G
ge-yafang 已提交
945
**示例:**
946

947
```js
D
duanweiling 已提交
948
try {
D
duanweiling 已提交
949
        data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
D
duanweiling 已提交
950
            if (err) {
D
duanweiling 已提交
951
                console.info("Failed to get preferences.");
D
duanweiling 已提交
952 953
                return;
            }
D
duanweiling 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
            let observer = function (key) {
                console.info("The key " + key + " changed.");
            }
            preferences.on('change', observer);
            preferences.put('startup', 'manual', function (err) {
                if (err) {
                    console.info("Failed to put the value of 'startup'. Cause: " + err);
                    return;
                }
                console.info("Succeeded in putting the value of 'startup'.");

                preferences.flush(function (err) {
                    if (err) {
                        console.info("Failed to flush. Cause: " + err);
                        return;
                    }
                    console.info("Succeeded in flushing."); // observer will be called.
                })
            })
D
duanweiling 已提交
973
        })
D
duanweiling 已提交
974 975 976
    } catch (err) {
        console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
    }
P
PaDaBoo 已提交
977
```
P
PaDoBoo 已提交
978 979 980 981


### off('change')

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

984
取消订阅数据变更。
P
PaDoBoo 已提交
985

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

G
ge-yafang 已提交
988
**参数:**
989

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

G
ge-yafang 已提交
995
**示例:**
996

997
```js
D
duanweiling 已提交
998
try {
D
duanweiling 已提交
999
    data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
D
duanweiling 已提交
1000
        if (err) {
D
duanweiling 已提交
1001
            console.info("Failed to get preferences.");
D
duanweiling 已提交
1002 1003
            return;
        }
D
duanweiling 已提交
1004 1005 1006 1007 1008
        let observer = function (key) {
            console.info("The key " + key + " changed.");
        }
        preferences.on('change', observer);
        preferences.put('startup', 'auto', function (err) {
D
duanweiling 已提交
1009
            if (err) {
D
duanweiling 已提交
1010
                console.info("Failed to put the value of 'startup'. Cause: " + err);
D
duanweiling 已提交
1011 1012
                return;
            }
D
duanweiling 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            console.info("Succeeded in putting the value of 'startup'.");

            preferences.flush(function (err) {
                if (err) {
                    console.info("Failed to flush. Cause: " + err);
                    return;
                }
                console.info("Succeeded in flushing."); // observer will be called.
            })
            preferences.off('change', observer);
D
duanweiling 已提交
1023 1024
        })
    })
D
duanweiling 已提交
1025 1026
} catch (err) {
    console.info("Failed to flush. code =" + err.code + ", message =" + err.message);}
P
PaDaBoo 已提交
1027
```
G
ge-yafang 已提交
1028 1029 1030 1031 1032

## ValueType

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

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

1035 1036 1037 1038 1039
| 类型            | 说明                           |
| --------------- | ------------------------------ |
| number          | 表示值类型为数字。             |
| string          | 表示值类型为字符串。           |
| boolean         | 表示值类型为布尔值。           |
1040 1041
| Array\<number>  | 表示值类型为数字类型的数组。   |
| Array\<boolean> | 表示值类型为布尔类型的数组。   |
1042
| Array\<string>  | 表示值类型为字符串类型的数组。 |