• 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';
17
18const NAME: string = "CONTACT_PREFERENCE";
19type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;
20
21class SharedPreferencesUtils {
22  private mPreferences: data_preferences.Preferences;
23
24  constructor() {
25    this.getPreferences().then((data) => {
26      this.mPreferences = data;
27    })
28  }
29
30  /**
31   * getFromPreferences
32   *
33   * @return the value get from Preferences
34   */
35  public async getFromPreferences(key: string, defValue) {
36    let preferences: data_preferences.Preferences = await this.getPreferences();
37    return await preferences.get(key, defValue);
38  }
39
40  /**
41   * saveToPreferences
42   *
43   * @param key save to Preferences
44   * @param value save to Preferences
45   */
46  public async saveToPreferences(key: string, value: ValueType) {
47    let preferences: data_preferences.Preferences = await this.getPreferences();
48    await preferences.put(key, value);
49    preferences.flush()
50  }
51
52  private async getPreferences() {
53    if (this.mPreferences) {
54      return this.mPreferences;
55    }
56    return await data_preferences.getPreferences(globalThis.context, NAME);
57  }
58}
59
60export default new SharedPreferencesUtils();