鸿蒙学习-preferences封装

学习记录一下,封装preferences

preferences:用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。

数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。

preferences有同步和异步操作两种方式,这里只封装了同步方法,大家可以参考使用

复制代码
import preferences from '@ohos.data.preferences';
class SpUtil {
  sp: preferences.Preferences
  constructor() {
    let options: preferences.Options = { name: '自定义' };
    this.sp = preferences.getPreferencesSync(getContext(this), options)
  }

  put(key: string, value: preferences.ValueType) {
    this.sp.putSync(key, value)
    this.sp.flush()
  }

  get(key: string, defValue: preferences.ValueType) {
    return this.sp.getSync(key, defValue)
  }

  clearAll() {
    this.sp.clearSync()
    this.sp.flush()
  }
}

export default new SpUtil()

文件存储路径:/data/app/el2/100/base/包名/haps/entry/preferences/文件名

使用:

复制代码
let isFirst = SpUtil.get("isFirst", true) as boolean
相关推荐
用户29469405448163 小时前
DSH Desktop - Electron on HarmonyOS Edition
harmonyos·deepseek
IsITGirl4 小时前
HarmonyOS 鸿蒙 WuKong 稳定性测试报错 Failed to connect to AAMS(已解决)
华为·harmonyos
万物智能信息科技6 小时前
鸿蒙RS232驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
驱动开发·华为·开源·harmonyos·鸿蒙
less_121388 小时前
鸿蒙 WPS Open SDK 接入指南:凭据申请、HAR 集成与 registerApp 校验
华为·harmonyos·wps
威哥爱编程1 天前
HarmonyOS 7 Agent 开发实战 07:多 Agent 任务分解与反思
agent·harmonyos
威哥爱编程1 天前
HarmonyOS 7 Agent 开发实战 06:Agent 记忆与上下文管理
agent·harmonyos
HarmonyOS_SDK1 天前
【HarmonyOS SDK Skills】扫码能力一键构建,系统级高精度扫码秒实现
harmonyos
结局无敌1 天前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
结局无敌1 天前
React Native for OpenHarmony 实战:三方库 react-native-paper 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·ecmascript·harmonyos
七月稻草人1 天前
鸿蒙手机远程控制电脑选哪个?2026 鸿蒙远控软件横评
智能手机·电脑·harmonyos