HarmonyOS 鸿蒙Next首选项preferences封装

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

HarmonyOS 鸿蒙Next首选项preferences封装
<markdown _ngcontent-tlg-c237="" class="markdownPreContainer">

1、EntryAbility获取Context并保存到AppStorage中,可直接在工具类中获取,无需传递

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppStorage.setOrCreate<Context>(Constant.KEY_CONTEXT_ABILITY,this.context)
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

2、PreferUtil非业务工具类

import { preferences } from '@kit.ArkData'
import { PreferConstant } from './PreferConstant'
import { Context } from '@kit.AbilityKit'
import { Constant } from '../app/Constant'

export class PreferUtil {

static getStore(){ const context = AppStorage.get<Context>(Constant.KEY_CONTEXT_ABILITY) return preferences.getPreferencesSync(context, { name: PreferConstant.APP_STORE_DEFAULT }) }

static put(key: string, value: preferences.ValueType) { const store = PreferUtil.getStore() store.putSync(key, value) store.flush() }

static get(key: string, defaultValue: preferences.ValueType) { const store = PreferUtil.getStore() return store.getSync(key, defaultValue) }

static delete(key: string) { const store = PreferUtil.getStore() store.deleteSync(key) store.flush() } } <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

3、分功能模块写管理工具类,如AppPreferHelper、UserHelper等

import { PreferConstant } from './PreferConstant'
import { PreferUtil } from './PreferUtil'

export class AppPreferHelper {

static saveToken(token: string) { PreferUtil.put(PreferConstant.KEY_TOKEN, token) }

static getToken() { return PreferUtil.get(PreferConstant.KEY_TOKEN, “”) as string }

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

4、常量类PreferConstant只放首选项相关

export class PreferConstant {

static APP_STORE_DEFAULT = “default_store” // 首选项仓库的key

static KEY_TOKEN=“token” static KEY_USER_INFO=“userinfo”

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

</markdown>

2 回复
缺少了异常处理~

HarmonyOS 鸿蒙Next首选项preferences封装主要用于应用配置信息的持久化存储。它支持Key-Value键值对形式,适用于轻量级数据存储,如用户个性化设置。封装时,需创建Preferences工具类,利用HarmonyOS的API如@ohos.data.preferences获取Preferences实例,并提供读写数据的方法。确保在需要时调用flush接口持久化数据。如果问题依旧没法解决请加我微信,我的微信是itying888。

回到顶部