适配版本:HarmonyOS 5.0.0 或以上
阅读目标:掌握 Preferences 本地持久化方案的使用,适用于开关项、配置项的保存与读取
🧱 一、什么是 Preferences?
Preferences
是 HarmonyOS 提供的轻量级结构化键值存储模块,支持持久化存储到本地文件系统,适合用于:
-
用户偏好设置(如是否开启推送)
-
简单配置项(如主题选择、是否第一次启动)
-
小体积状态缓存(适合结构化访问)
✔ 与
LocalStorage
不同,Preferences 是真正落盘存储,并支持异步读取写入
🧰 二、模块导入与创建 Preferences 实例
import preferences from '@ohos.data.preferences'
let prefs: preferences.Preferences
async function initPrefs() {
prefs = await preferences.getPreferences(getContext(this), 'user_config')
}
📁 'user_config'
为你定义的文件名,存储路径为私有沙盒目录。
🧪 三、保存与读取布尔值配置项(开关按钮)
示例场景:是否开启消息推送
@Entry
@Component
struct PushSetting {
@State enablePush: boolean = false
async aboutToAppear() {
const prefs = await preferences.getPreferences(getContext(this), 'user_config')
this.enablePush = await prefs.get('push_enabled', false)
}
async togglePush(value: boolean) {
this.enablePush = value
const prefs = await preferences.getPreferences(getContext(this), 'user_config')
await prefs.put('push_enabled', value)
await prefs.flush() // ⚠️ 必须 flush() 才会写入文件
}
build() {
Column() {
Text('是否开启推送通知')
.fontSize(18)
.margin({ bottom: 10 })
Toggle({ checked: this.enablePush })
.onChange(val => this.togglePush(val))
}
.padding(20)
}
}
🧩 四、支持的数据类型
类型 | 使用方法示例 |
---|---|
string | prefs.put('nickname', '张三') |
number | prefs.put('age', 15) |
boolean | prefs.put('vip', true) |
object | ❌ 不支持直接存对象(建议转 JSON) |
⚠️ 若需存储数组或对象,请先
JSON.stringify()
,读取后再JSON.parse()
🧾 五、完整封装:读取 + 写入工具函数
export async function setConfig(key: string, value: string | boolean | number) {
const prefs = await preferences.getPreferences(getContext(globalThis), 'user_config')
await prefs.put(key, value)
await prefs.flush()
}
export async function getConfig<T = any>(key: string, defaultVal: T): Promise<T> {
const prefs = await preferences.getPreferences(getContext(globalThis), 'user_config')
return prefs.get(key, defaultVal)
}
✅ 六、小结
能力点 | 实践说明 |
---|---|
适用场景 | 设置项、本地标志位、开关状态等 |
支持类型 | string、number、boolean,复杂对象需转 JSON |
与 LocalStorage 区别 | Preferences 为异步、持久化落盘存储方式 |
写入注意事项 | 写入后必须调用 flush() 否则不会真正写入文件 |
📘 下一篇预告
第16篇|使用数据库 RelationalStore 存储结构化对象:适合本地表结构数据管理
将介绍如何用 HarmonyOS 提供的 SQLite 兼容接口进行复杂数据存储,如用户列表、打卡记录等。