一、工具类:PreferencesUtil.ets
工具类,包括创建Preferences首选项、保存和获取对应Key的数据等方法
示例代码中以保存Token字符串值为例:
import { preferences } from '@kit.ArkData'; import { GlobalContext } from './GlobalContext'; const PREFERENCES_NAME = 'currPreferences'; const KEY_APP_LOGIN_TOKEN = 'loginToken'; /** * 首选项-工具类 保存应用数据 */ export class PreferencesUtil { createPreferences(context: Context) { let currPreferences: Function = (() => { return preferences.getPreferences(context, {name: PREFERENCES_NAME}); }) GlobalContext.getContext().setObject('getPreferences',currPreferences); } /** * 保存Token * @param token */ saveLoginToken(token: string){ let currPreferences: Function = GlobalContext.getContext().getObject('getPreferences') as Function; currPreferences().then((preferences: preferences.Preferences) => { preferences.put(KEY_APP_LOGIN_TOKEN, token); preferences.flush(); }); } /** * 获取Token * @returns */ async getLoginToken(){ let currPreferences: Function = GlobalContext.getContext().getObject('getPreferences') as Function; let token: string = await (await currPreferences()).get(KEY_APP_LOGIN_TOKEN, ''); return token; } } export default new PreferencesUtil();
GlobalContext.ets
export class GlobalContext { private constructor() { } private static instance: GlobalContext; private _objects = new Map<string, Object>(); public static getContext(): GlobalContext { if (!GlobalContext.instance) { GlobalContext.instance = new GlobalContext(); } return GlobalContext.instance; } getObject(value: string): Object | undefined { return this._objects.get(value); } setObject(key: string, objectClass: Object): void { this._objects.set(key, objectClass); } }
二、使用
1、EntryAbility.ets中的onCreate()方法中调用相应方法创建首选项示例
export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); //添加以下方法调用代码 GlobalContext.getContext().setObject('abilityWant', want); PreferencesUtil.createPreferences(this.context); } ... }
2、保存Token值
直接调用工具类的方法
PreferencesUtil.saveLoginToken('xxx');
3、获取保存的Token值
PreferencesUtil.getLoginToken().then((value) => { //value就是获取到的值 });