1/** 2 * Copyright (c) 2024-2024 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 DataPreferences from '@ohos.data.preferences'; 17import { Log } from '../utils/Log'; 18import { Context } from '@ohos.abilityAccessCtrl'; 19 20 21const TAG = 'PreferencesHelper'; 22 23export class PreferencesHelper { 24 private static PREFERENCE_NAME = 'launcher_pref'; 25 private static sInstance:PreferencesHelper | undefined = undefined; 26 private preference:DataPreferences.Preferences; 27 28 static getInstance() { 29 if (!PreferencesHelper.sInstance) { 30 PreferencesHelper.sInstance = new PreferencesHelper(); 31 } 32 return PreferencesHelper.sInstance; 33 } 34 35 async initPreference(context: Context): Promise<void> { 36 if (this.preference) { 37 Log.showInfo(TAG, 'preference is inited'); 38 return; 39 } 40 try { 41 this.preference = await DataPreferences.getPreferences(context, PreferencesHelper.PREFERENCE_NAME); 42 } catch (err) { 43 Log.showError(TAG, `Failed to initPreference, Cause:${err.message || err?.code}`); 44 } 45 } 46 47 async put(key:string, value):Promise<void>{ 48 try { 49 await this.preference?.put(key,value); 50 } catch (err) { 51 Log.showError(TAG, `Failed to put value, Cause:${err.message || err?.code}`); 52 } 53 await this.preference?.flush(); 54 } 55 56 async get(key:string, defValue):Promise<DataPreferences.ValueType>{ 57 try { 58 let result = await this.preference?.get(key,defValue); 59 return result; 60 } catch (err) { 61 Log.showError(TAG, `Failed to get initPreferences, Cause:${err.message || err?.code}`); 62 } 63 return defValue; 64 } 65} 66