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 private context: Context; 24 25 constructor() { 26 this.getPreferences().then((data) => { 27 this.mPreferences = data; 28 }) 29 } 30 31 /* 32 * init if Call From serviceAbility globalThis.context is Null 33 *@param ctx Context used for dataShare 34 */ 35 init(ctx: Context) { 36 this.context = ctx; 37 } 38 39 /** 40 * getFromPreferences 41 * 42 * @return the value get from Preferences 43 */ 44 public async getFromPreferences(key: string, defValue) { 45 let preferences: data_preferences.Preferences = await this.getPreferences(); 46 return await preferences.get(key, defValue); 47 } 48 49 /** 50 * saveToPreferences 51 * 52 * @param key save to Preferences 53 * @param value save to Preferences 54 */ 55 public async saveToPreferences(key: string, value: ValueType) { 56 let preferences: data_preferences.Preferences = await this.getPreferences(); 57 await preferences.put(key, value); 58 preferences.flush() 59 } 60 61 private async getPreferences() { 62 if (this.mPreferences) { 63 return this.mPreferences; 64 } 65 return await data_preferences.getPreferences(globalThis.context ? globalThis.context : this.context, NAME); 66 } 67} 68 69export const sharedPreferencesUtils: SharedPreferencesUtils = new SharedPreferencesUtils();