js-apis-data-preferences.md 36.1 KB
Newer Older
Z
zengyawen 已提交
1
# @ohos.data.preferences (首选项)
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   | number   | 是   | 否   | Key的最大长度限制为80个字节。     |
| MAX_VALUE_LENGTH | number   | 是   | 否   | 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-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.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
	        console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
	        return;
	    }
61
	    preferences = val;
D
duanweiling 已提交
62 63
	    console.info("Succeeded in getting preferences.");
	})
D
duanweiling 已提交
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
Stage模型示例:

```ts
72 73
import UIAbility from '@ohos.app.ability.UIAbility';

W
wangxiyue 已提交
74
let preferences = null;
75 76

class EntryAbility extends UIAbility {
W
wangxiyue 已提交
77 78 79 80 81 82 83
    onWindowStageCreate(windowStage) {
        try {
            data_preferences.getPreferences(this.context, 'mystore', function (err, val) {
                if (err) {
                    console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
84
                preferences = val;
W
wangxiyue 已提交
85 86 87 88 89
                console.info("Succeeded in getting preferences.");
            })
        } catch (err) {
            console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
        }
90 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-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.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
    let promise = data_preferences.getPreferences(context, 'mystore');
    promise.then((object) => {
D
duanweiling 已提交
128 129
        preferences = object;
        console.info("Succeeded in getting preferences.");
D
duanweiling 已提交
130
    }).catch((err) => {
W
wangxiyue 已提交
131
        console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
132 133
    })
} catch(err) {
W
wangxiyue 已提交
134
    console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
135
}
P
PaDaBoo 已提交
136
```
P
PaDoBoo 已提交
137

138 139 140
Stage模型示例:

```ts
141 142
import UIAbility from '@ohos.app.ability.UIAbility';

W
wangxiyue 已提交
143
let preferences = null;
144 145

class EntryAbility extends UIAbility {
W
wangxiyue 已提交
146 147 148 149 150 151 152 153 154 155 156 157
    onWindowStageCreate(windowStage) {
        try {
            let promise = data_preferences.getPreferences(this.context, 'mystore');
            promise.then((object) => {
                preferences = object;
                console.info("Succeeded in getting preferences.");
            }).catch((err) => {
                console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch(err) {
            console.info("Failed to get preferences. code =" + err.code + ", message =" + err.message);
        }
158 159 160
    }
}
```
P
PaDoBoo 已提交
161

162
## data_preferences.deletePreferences
P
PaDoBoo 已提交
163

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

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

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

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

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

G
ge-yafang 已提交
174
**参数:**
175

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

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

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

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

G
ge-yafang 已提交
190
**示例:**
191

192 193
FA模型示例:

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

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

212 213 214
Stage模型示例:

```ts
215 216 217
import UIAbility from '@ohos.app.ability.UIAbility';

class EntryAbility extends UIAbility {
W
wangxiyue 已提交
218 219 220 221 222 223 224 225 226 227
    onWindowStageCreate(windowStage) {
        try {
            data_preferences.deletePreferences(this.context, 'mystore', function (err, val) {
                if (err) {
                    console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in deleting preferences." );
            })
        } catch (err) {
D
duanweiling 已提交
228
            console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
229
        }
W
wangxiyue 已提交
230
    }
D
duanweiling 已提交
231
}
232
```
P
PaDoBoo 已提交
233

234
## data_preferences.deletePreferences
P
PaDoBoo 已提交
235

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

238 239 240
从内存中移除指定的Preferences实例,使用Promise异步回调。

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

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

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

G
ge-yafang 已提交
246
**参数:**
247 248 249

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

D
duanweiling 已提交
253 254 255 256 257 258
**返回值:**

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

D
duanweiling 已提交
259 260 261 262 263 264 265 266
**错误码:**

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

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

G
ge-yafang 已提交
267
**示例:**
268

269 270
FA模型示例:

271
```js
272
// 获取context
273 274
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
275

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

288 289 290
Stage模型示例:

```ts
291 292 293
import UIAbility from '@ohos.app.ability.UIAbility';

class EntryAbility extends UIAbility {
W
wangxiyue 已提交
294 295 296 297 298 299 300 301 302 303 304
    onWindowStageCreate(windowStage) {
        try{
            let promise = data_preferences.deletePreferences(this.context, 'mystore');
            promise.then(() => {
                console.info("Succeeded in deleting preferences.");
            }).catch((err) => {
                console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch(err) {
            console.info("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
        }
305 306 307
    }
}
```
P
PaDoBoo 已提交
308

309
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
310

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

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

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

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

G
ge-yafang 已提交
319
**参数:**
320

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

G
ge-yafang 已提交
327
**示例:**
328

329 330
FA模型示例:

331
```js
332
// 获取context
333 334
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
335

D
duanweiling 已提交
336
try {
D
duanweiling 已提交
337
    data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
D
duanweiling 已提交
338
        if (err) {
D
duanweiling 已提交
339 340
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
341
        }
D
duanweiling 已提交
342 343
        console.info("Succeeded in removing preferences.");
    })
D
duanweiling 已提交
344
} catch (err) {
D
duanweiling 已提交
345
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
346
}
P
PaDaBoo 已提交
347
```
P
PaDoBoo 已提交
348

349 350 351
Stage模型示例:

```ts
352 353 354
import UIAbility from '@ohos.app.ability.UIAbility';

class EntryAbility extends UIAbility {
W
wangxiyue 已提交
355 356 357 358 359 360 361 362 363 364
    onWindowStageCreate(windowStage) {
        try {
            data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err, val) {
                if (err) {
                    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in removing preferences.");
            })
        } catch (err) {
D
duanweiling 已提交
365
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
366
        }
W
wangxiyue 已提交
367
    }
D
duanweiling 已提交
368
}
D
duanweiling 已提交
369

370
```
P
PaDoBoo 已提交
371

372
## data_preferences.removePreferencesFromCache
P
PaDoBoo 已提交
373

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

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

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

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

G
ge-yafang 已提交
382
**参数:**
383 384 385

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

G
ge-yafang 已提交
389
**返回值:**
390

391 392 393
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
394

G
ge-yafang 已提交
395
**示例:**
396

397 398
FA模型示例:

399
```js
400
// 获取context
401 402
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
403

D
duanweiling 已提交
404
try {
D
duanweiling 已提交
405 406 407
    let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
	promise.then(() => {
    	console.info("Succeeded in removing preferences.");
D
duanweiling 已提交
408
    }).catch((err) => {
D
duanweiling 已提交
409
        console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
410 411
    })
} catch(err) {
D
duanweiling 已提交
412
    console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
413
}
P
PaDaBoo 已提交
414
```
P
PaDoBoo 已提交
415

416 417 418
Stage模型示例:

```ts
419
import UIAbility from '@ohos.app.ability.UIAbility';
W
wangxiyue 已提交
420

421
class EntryAbility extends UIAbility {
W
wangxiyue 已提交
422 423 424 425 426 427 428 429 430 431 432
    onWindowStageCreate(windowStage) {
        try {
            let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore');
            promise.then(() => {
                console.info("Succeeded in removing preferences.");
            }).catch((err) => {
                console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch(err) {
            console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
        }
433 434 435
    }
}
```
P
PaDoBoo 已提交
436 437 438

## Preferences

439 440 441
存储实例,提供获取和修改存储数据的接口。

下列接口都需先使用[data_preferences.getPreferences](#data_preferencesgetpreferences)获取到Preferences实例,再通过此实例调用对应接口。
P
PaDoBoo 已提交
442 443 444 445 446 447


### get

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

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

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

G
ge-yafang 已提交
452
**参数:**
453

454 455 456 457 458
| 参数名   | 类型                                         | 必填 | 说明                                                         |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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 已提交
459

G
ge-yafang 已提交
460
**示例:**
461 462

```js
D
duanweiling 已提交
463
try {
464
    preferences.get('startup', 'default', function (err, val) {
D
duanweiling 已提交
465
        if (err) {
D
duanweiling 已提交
466 467
            console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
468
        }
D
duanweiling 已提交
469
        console.info("Succeeded in getting value of 'startup'. val: " + val);
D
duanweiling 已提交
470 471
    })
} catch (err) {
D
duanweiling 已提交
472
    console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
473
}
P
PaDaBoo 已提交
474
```
P
PaDoBoo 已提交
475 476 477 478 479 480


### get

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

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

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

485
 **参数:**
486

487 488 489 490
| 参数名   | 类型                    | 必填 | 说明                                                         |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key      | string                  | 是   | 要获取的存储Key名称,不能为空。                              |
| defValue | [ValueType](#valuetype) | 是   | 默认返回值。支持number、string、boolean、Array\<number>、Array\<string>、Array\<boolean>类型。 |
P
PaDoBoo 已提交
491

G
ge-yafang 已提交
492
**返回值:**
493 494 495 496

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

G
ge-yafang 已提交
498
**示例:**
499

500
```js
D
duanweiling 已提交
501
try {
D
duanweiling 已提交
502 503 504
    let promise = preferences.get('startup', 'default');
    promise.then((data) => {
        console.info("Succeeded in getting value of 'startup'. Data: " + data);
D
duanweiling 已提交
505
    }).catch((err) => {
D
duanweiling 已提交
506
        console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
507 508
    })
} catch(err) {
D
duanweiling 已提交
509
    console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
510
}
P
PaDaBoo 已提交
511
```
P
PaDoBoo 已提交
512

513 514 515 516
### getAll

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

517
获取含有所有键值的Object对象。
518 519 520 521

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

**参数:**
522

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

**示例:**
528 529

```js
D
duanweiling 已提交
530
try {
D
duanweiling 已提交
531
    preferences.getAll(function (err, value) {
D
duanweiling 已提交
532
        if (err) {
D
duanweiling 已提交
533 534
            console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
535
        }
D
duanweiling 已提交
536 537 538
    let allKeys = Object.keys(value);
    console.info("getAll keys = " + allKeys);
    console.info("getAll object = " + JSON.stringify(value));
D
duanweiling 已提交
539 540
    })
} catch (err) {
D
duanweiling 已提交
541
    console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
542
}
543 544 545 546 547 548 549
```


### getAll

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

550
获取含有所有键值的Object对象。
551 552 553 554

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

**返回值:**
555

556 557 558
| 类型                  | 说明                                        |
| --------------------- | ------------------------------------------- |
| Promise&lt;Object&gt; | Promise对象,返回含有所有键值的Object对象。 |
559 560

**示例:**
561

562
```js
D
duanweiling 已提交
563
try {
D
duanweiling 已提交
564 565
    let promise = preferences.getAll();
    promise.then((value) => {
D
duanweiling 已提交
566 567 568
        let allKeys = Object.keys(value);
        console.info('getAll keys = ' + allKeys);
        console.info("getAll object = " + JSON.stringify(value));
D
duanweiling 已提交
569
    }).catch((err) => {
D
duanweiling 已提交
570
        console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
571 572
    })
} catch (err) {
D
duanweiling 已提交
573
    console.info("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
574
}
575
```
P
PaDoBoo 已提交
576 577 578 579 580

### put

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

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

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

G
ge-yafang 已提交
585
**参数:**
586

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

G
ge-yafang 已提交
593
**示例:**
594

595
```js
D
duanweiling 已提交
596
try {
D
duanweiling 已提交
597
    preferences.put('startup', 'auto', function (err) {
D
duanweiling 已提交
598
        if (err) {
D
duanweiling 已提交
599
            console.info("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
600
            return;
D
duanweiling 已提交
601
        }
D
duanweiling 已提交
602
        console.info("Succeeded in putting value of 'startup'.");
D
duanweiling 已提交
603
    })
D
duanweiling 已提交
604
} catch (err) {
D
duanweiling 已提交
605
    console.info("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
606
}
P
PaDaBoo 已提交
607
```
P
PaDoBoo 已提交
608 609 610 611 612 613


### put

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

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

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

G
ge-yafang 已提交
618
**参数:**
619

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

G
ge-yafang 已提交
625
**返回值:**
626

627 628 629
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
630

G
ge-yafang 已提交
631
**示例:**
632

633
```js
D
duanweiling 已提交
634
try {
D
duanweiling 已提交
635
    let promise = preferences.put('startup', 'auto');
D
duanweiling 已提交
636
    promise.then(() => {
D
duanweiling 已提交
637
        console.info("Succeeded in putting value of 'startup'.");
D
duanweiling 已提交
638
    }).catch((err) => {
D
duanweiling 已提交
639
        console.info("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
640 641
    })
} catch(err) {
D
duanweiling 已提交
642
    console.info("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
643
}
P
PaDaBoo 已提交
644
```
P
PaDoBoo 已提交
645 646 647 648


### has

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

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

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

G
ge-yafang 已提交
655
**参数:**
656

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

G
ge-yafang 已提交
662
**示例:**
663

664
```js
D
duanweiling 已提交
665
try {
D
duanweiling 已提交
666
    preferences.has('startup', function (err, val) {
D
duanweiling 已提交
667 668 669 670 671 672 673 674 675
        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 已提交
676
  })
D
duanweiling 已提交
677 678
} catch (err) {
    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
679
}
P
PaDaBoo 已提交
680
```
P
PaDoBoo 已提交
681 682 683 684 685 686


### has

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

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

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

G
ge-yafang 已提交
691
**参数:**
692

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

G
ge-yafang 已提交
697
**返回值:**
698

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

G
ge-yafang 已提交
703
**示例:**
704 705

```js
D
duanweiling 已提交
706
try {
D
duanweiling 已提交
707 708
    let promise = preferences.has('startup');
    promise.then((val) => {
D
duanweiling 已提交
709
        if (val) {
D
duanweiling 已提交
710
            console.info("The key 'startup' is contained.");
D
duanweiling 已提交
711
        } else {
D
duanweiling 已提交
712
            console.info("The key 'startup' dose not contain.");
D
duanweiling 已提交
713
        }
D
duanweiling 已提交
714
    }).catch((err) => {
D
duanweiling 已提交
715
        console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
716 717
  })
} catch(err) {
D
duanweiling 已提交
718
    console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
719
}
P
PaDaBoo 已提交
720
```
P
PaDoBoo 已提交
721 722 723 724 725 726


### delete

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

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

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

G
ge-yafang 已提交
731
**参数:**
732

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

G
ge-yafang 已提交
738
**示例:**
739

740
```js
D
duanweiling 已提交
741
try {
D
duanweiling 已提交
742
    preferences.delete('startup', function (err) {
D
duanweiling 已提交
743
        if (err) {
D
duanweiling 已提交
744 745
            console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
746
        }
D
duanweiling 已提交
747
        console.info("Succeeded in deleting the key 'startup'.");
D
duanweiling 已提交
748
    })
D
duanweiling 已提交
749 750
} catch (err) {
    console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
751
}
P
PaDaBoo 已提交
752
```
P
PaDoBoo 已提交
753 754 755 756 757 758


### delete

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

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

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

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

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

G
ge-yafang 已提交
769
**返回值:**
770

771 772 773
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
774

G
ge-yafang 已提交
775
**示例:**
776

777
```js
D
duanweiling 已提交
778
try {
D
duanweiling 已提交
779
    let promise = preferences.delete('startup');
D
duanweiling 已提交
780
	promise.then(() => {
D
duanweiling 已提交
781
        console.info("Succeeded in deleting the key 'startup'.");
D
duanweiling 已提交
782
    }).catch((err) => {
W
wangxiyue 已提交
783
        console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
784 785
    })
} catch(err) {
W
wangxiyue 已提交
786
    console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
D
duanweiling 已提交
787
}
P
PaDaBoo 已提交
788
```
P
PaDoBoo 已提交
789 790 791 792 793 794


### flush

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

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

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

G
ge-yafang 已提交
799
**参数:**
800

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

G
ge-yafang 已提交
805
**示例:**
806

807
```js
D
duanweiling 已提交
808
try {
D
duanweiling 已提交
809
    preferences.flush(function (err) {
D
duanweiling 已提交
810
        if (err) {
D
duanweiling 已提交
811 812
            console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
813
        }
D
duanweiling 已提交
814
        console.info("Succeeded in flushing.");
D
duanweiling 已提交
815
    })
D
duanweiling 已提交
816 817
} catch (err) {
    console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
818
}
P
PaDaBoo 已提交
819
```
P
PaDoBoo 已提交
820 821 822 823 824 825


### flush

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

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

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

G
ge-yafang 已提交
830
**返回值:**
831

832 833 834
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
835

G
ge-yafang 已提交
836
**示例:**
837

838
```js
D
duanweiling 已提交
839
try {
D
duanweiling 已提交
840
    let promise = preferences.flush();
D
duanweiling 已提交
841
    promise.then(() => {
D
duanweiling 已提交
842
        console.info("Succeeded in flushing.");
D
duanweiling 已提交
843
    }).catch((err) => {
D
duanweiling 已提交
844
        console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
845 846
    })
} catch (err) {
D
duanweiling 已提交
847
    console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
848
}
P
PaDaBoo 已提交
849
```
P
PaDoBoo 已提交
850 851 852 853 854 855


### clear

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

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

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

G
ge-yafang 已提交
860
**参数:**
861

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

G
ge-yafang 已提交
866
**示例:**
867

868
```js
D
duanweiling 已提交
869 870 871
try {
	preferences.clear(function (err) {
        if (err) {
D
duanweiling 已提交
872 873
            console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
            return;
D
duanweiling 已提交
874
        }
D
duanweiling 已提交
875
        console.info("Succeeded in clearing.");
D
duanweiling 已提交
876
    })
D
duanweiling 已提交
877
} catch (err) {
D
duanweiling 已提交
878
    console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
879
}
P
PaDaBoo 已提交
880
```
P
PaDoBoo 已提交
881 882 883 884 885 886


### clear

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

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

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

G
ge-yafang 已提交
891
**返回值:**
892

893 894 895
| 类型                | 说明                      |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
P
PaDoBoo 已提交
896

G
ge-yafang 已提交
897
**示例:**
898

899
```js
D
duanweiling 已提交
900 901
try {
    let promise = preferences.clear();
D
duanweiling 已提交
902 903
	promise.then(() => {
    	console.info("Succeeded in clearing.");
D
duanweiling 已提交
904
    }).catch((err) => {
D
duanweiling 已提交
905
        console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
906 907
    })
} catch(err) {
D
duanweiling 已提交
908
    console.info("Failed to clear. code =" + err.code + ", message =" + err.message);
D
duanweiling 已提交
909
}
P
PaDaBoo 已提交
910
```
P
PaDoBoo 已提交
911 912 913 914 915 916


### on('change')

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

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

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

G
ge-yafang 已提交
921
**参数:**
922

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

G
ge-yafang 已提交
928
**示例:**
929

930
```js
D
duanweiling 已提交
931
try {
D
duanweiling 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
	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', '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;
				}
D
duanweiling 已提交
953
				console.info("Succeeded in flushing.");
D
duanweiling 已提交
954 955 956 957 958 959
			})
		})
	})
} catch (err) {
	console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
}
P
PaDaBoo 已提交
960
```
P
PaDoBoo 已提交
961 962 963 964


### off('change')

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

967
取消订阅数据变更。
P
PaDoBoo 已提交
968

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

G
ge-yafang 已提交
971
**参数:**
972

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

G
ge-yafang 已提交
978
**示例:**
979

980
```js
D
duanweiling 已提交
981
try {
D
duanweiling 已提交
982
    data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
D
duanweiling 已提交
983
        if (err) {
D
duanweiling 已提交
984
            console.info("Failed to get preferences.");
D
duanweiling 已提交
985 986
            return;
        }
D
duanweiling 已提交
987 988 989 990 991
        let observer = function (key) {
            console.info("The key " + key + " changed.");
        }
        preferences.on('change', observer);
        preferences.put('startup', 'auto', function (err) {
D
duanweiling 已提交
992
            if (err) {
D
duanweiling 已提交
993
                console.info("Failed to put the value of 'startup'. Cause: " + err);
D
duanweiling 已提交
994 995
                return;
            }
D
duanweiling 已提交
996 997 998 999 1000 1001 1002
            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 已提交
1003
                console.info("Succeeded in flushing.");
D
duanweiling 已提交
1004 1005
            })
            preferences.off('change', observer);
D
duanweiling 已提交
1006 1007
        })
    })
D
duanweiling 已提交
1008
} catch (err) {
D
duanweiling 已提交
1009 1010
    console.info("Failed to flush. code =" + err.code + ", message =" + err.message);
}
P
PaDaBoo 已提交
1011
```
G
ge-yafang 已提交
1012 1013 1014 1015 1016

## ValueType

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

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

1019 1020 1021 1022 1023
| 类型            | 说明                           |
| --------------- | ------------------------------ |
| number          | 表示值类型为数字。             |
| string          | 表示值类型为字符串。           |
| boolean         | 表示值类型为布尔值。           |
1024 1025
| Array\<number>  | 表示值类型为数字类型的数组。   |
| Array\<boolean> | 表示值类型为布尔类型的数组。   |
1026
| Array\<string>  | 表示值类型为字符串类型的数组。 |