• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import data_preferences from '@ohos.data.preferences';
17import contextConstant from '@ohos.app.ability.contextConstant'
18
19const NAME: string = "CONTACT_PREFERENCE";
20type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;
21
22class SharedPreferencesUtils {
23  private mPreferences: data_preferences.Preferences;
24  private context: Context;
25
26  constructor() {
27    this.getPreferences().then((data) => {
28      this.mPreferences = data;
29    })
30  }
31
32  /*
33   * init if Call From serviceAbility globalThis.context is Null
34   *@param ctx Context used for dataShare
35   */
36  init(ctx: Context) {
37    this.context = ctx;
38  }
39
40  /**
41   * getFromPreferences
42   *
43   * @return the value get from Preferences
44   */
45  public async getFromPreferences(key: string, defValue) {
46    let preferences: data_preferences.Preferences = await this.getPreferences();
47    return await preferences.get(key, defValue);
48  }
49
50  /**
51   * saveToPreferences
52   *
53   * @param key save to Preferences
54   * @param value save to Preferences
55   */
56  public async saveToPreferences(key: string, value: ValueType) {
57    let preferences: data_preferences.Preferences = await this.getPreferences();
58    await preferences.put(key, value);
59    preferences.flush()
60  }
61
62  private async getPreferences() {
63    if (this.mPreferences) {
64      return this.mPreferences;
65    }
66    let ctx: Context = this.context ? this.context : globalThis.context;
67    ctx.area = contextConstant.AreaMode.EL1
68    return await data_preferences.getPreferences(ctx, NAME);
69  }
70}
71
72export const sharedPreferencesUtils: SharedPreferencesUtils = new SharedPreferencesUtils();