js-apis-data-preferences.md 35.7 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
    data_preferences.getPreferences(context, 'mystore', function (err, val) {
D
duanweiling 已提交
57
        if (err) {
D
duanweiling 已提交
58 59
            console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
60
        }
D
duanweiling 已提交
61 62
        preferences = object;
        console.info("Succeeded in getting preferences.");
D
duanweiling 已提交
63 64
    })
} catch (err) {
D
duanweiling 已提交
65
    console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
66
}
P
PaDaBoo 已提交
67
```
P
PaDoBoo 已提交
68

69 70 71 72
Stage模型示例:

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

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

96
## data_preferences.getPreferences
P
PaDoBoo 已提交
97

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

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

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

G
ge-yafang 已提交
104
**参数:**
105 106 107

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

G
ge-yafang 已提交
111
**返回值:**
112

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

G
ge-yafang 已提交
117
**示例:**
118

119 120
FA模型示例:

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

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

140 141 142 143
Stage模型示例:

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

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

165
```
P
PaDoBoo 已提交
166

167
## data_preferences.deletePreferences
P
PaDoBoo 已提交
168

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

171 172 173
从内存中移除指定的Preferences实例,使用callback异步回调。

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

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

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

G
ge-yafang 已提交
179
**参数:**
180

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

D
duanweiling 已提交
187 188 189 190 191 192 193 194
**错误码:**

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

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

G
ge-yafang 已提交
195
**示例:**
196

197 198
FA模型示例:

199
```js
200
// 获取context
201 202
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
203

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

217 218 219 220
Stage模型示例:

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

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

242
## data_preferences.deletePreferences
P
PaDoBoo 已提交
243

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

246 247 248
从内存中移除指定的Preferences实例,使用Promise异步回调。

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

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

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

G
ge-yafang 已提交
254
**参数:**
255 256 257

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

D
duanweiling 已提交
261 262 263 264 265 266
**返回值:**

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

D
duanweiling 已提交
267 268 269 270 271 272 273 274
**错误码:**

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

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

G
ge-yafang 已提交
275
**示例:**
276

277 278
FA模型示例:

279
```js
280
// 获取context
281 282
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
283

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

296 297 298 299
Stage模型示例:

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

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

320
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
321

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

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

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

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

G
ge-yafang 已提交
330
**参数:**
331

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

G
ge-yafang 已提交
338
**示例:**
339

340 341
FA模型示例:

342
```js
343
// 获取context
344 345
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
346

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

360 361 362 363
Stage模型示例:

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

D
duanweiling 已提交
372
try {
D
duanweiling 已提交
373 374 375 376
    data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
         if (err) {
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
377
        }
D
duanweiling 已提交
378 379
    console.info("Succeeded in removing preferences.");
})
D
duanweiling 已提交
380
} catch (err) {
D
duanweiling 已提交
381
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
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
    console.info("Succeeded in getting value of 'startup'. val: " + val);
D
duanweiling 已提交
486 487
    })
} catch (err) {
D
duanweiling 已提交
488
        console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
489
}
P
PaDaBoo 已提交
490
```
P
PaDoBoo 已提交
491 492 493 494 495 496


### get

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

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

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

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

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

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

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

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

529 530 531 532
### getAll

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

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

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

**参数:**
538

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

**示例:**
544 545

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


### getAll

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

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

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

**返回值:**
571

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

**示例:**
577

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

### put

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

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

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

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

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

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

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


### put

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

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

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

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

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

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

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

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

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


### has

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

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

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

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

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

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

680
```js
D
duanweiling 已提交
681 682
    try{
      preferences.has('startup', function (err, val) {
D
duanweiling 已提交
683
        if (err) {
D
duanweiling 已提交
684 685 686 687 688 689 690
          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 已提交
691
        }
D
duanweiling 已提交
692
      })
D
duanweiling 已提交
693 694
} catch (err) {
    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
695
}
P
PaDaBoo 已提交
696
```
P
PaDoBoo 已提交
697 698 699 700 701 702


### has

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

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

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

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

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

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

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

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

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

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 797 798
   let promise = preferences.delete('startup');
	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 858 859
    let promise = preferences.flush();
promise.then(() => {
    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 919 920
    	let promise = preferences.clear()
	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 951 952 953 954 955 956 957 958 959 960 961
    if (err) {
        console.info("Failed to get preferences.");
        return;
    }
    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;
P
PaDaBoo 已提交
962
        }
D
duanweiling 已提交
963 964 965 966 967 968 969
        console.info("Succeeded in putting the value of 'startup'.");

        preferences.flush(function (err) {
            if (err) {
                console.info("Failed to flush. Cause: " + err);
                return;
            }
D
duanweiling 已提交
970 971 972 973
            console.info("Succeeded in flushing."); // observer will be called.
        })
    })
})
D
duanweiling 已提交
974
} catch (error) {
D
duanweiling 已提交
975
     console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
976
}
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 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
    if (err) {
        console.info("Failed to get preferences.");
        return;
    }
    let observer = function (key) {
        console.info("The key " + key + " changed.");
    }
    preferences.on('change', observer);
    preferences.put('startup', 'auto', 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.
        })
        preferences.off('change', observer);
    })
})
D
duanweiling 已提交
1025
} catch (error) {
D
duanweiling 已提交
1026
  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>  | 表示值类型为字符串类型的数组。 |