当前位置: 首页 > news >正文

鸿蒙:Preferences持久化实现方案

前言:

我们在使用很多app时,都会发现搜索记录在杀掉后台后进入依然还在,这极可能是用了持久化数据方案。这篇博客分享使用鸿蒙Preferences实现持久化方案,相信你看完后会有所收获。

我们还是老样子,跟着官方文档学习与实践,链接如下:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-data-preferences#preferencesgetpreferenceshttps://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-data-preferences#preferencesgetpreferences看完了,就来做个Demo练一练,本人整理的运行效果图和代码如下:

1、Index.ets

import { getPreferencesUtil, PreferencesUtil } from "./PreferencesUtil"@Entry
@Component
export struct Index {preferences: PreferencesUtil | undefined = undefined@State message: string[] = ["Hello World", "番茄", "持久化", "杯子", "奶茶"]@State index: number = 0context: Context = this.getUIContext().getHostContext() as ContextaboutToAppear(): void {this.preferences = getPreferencesUtil()}@BuildertextBuilder() {Column({ space: 20 }) {Text(this.message[this.index])Button("持久化当前字符串,并切换下一个字符串").onClick(() => {this.index = Math.floor(Math.random() * 5)this.preferences?.put(this.context,this.message[this.index])})}}build() {Column({ space: 30 }) {this.textBuilder()Button("获取持久化字符串列表").onClick(async () => {const list = await this.preferences?.get(this.context)if (list) {this.getUIContext().showAlertDialog({ message: list.toString() })}})}.justifyContent(FlexAlign.Center).width("100%").height("100%")}
}

2、PreferencesUtil.ets

import { preferences } from '@kit.ArkData';/** 偏好设置工具类,用于管理字符串数组类型的偏好数据 */
export class PreferencesUtil {/** 偏好设置数据对象 */private dataPreferences: preferences.Preferences | null = null;/** 上下文对象 */private context: Context | null = null;/** 偏好设置存储名称 */private name: string = 'preferences';/*** 初始化工具类* @param context 上下文对象*/public init(context: Context) {this.context = context;this.dataPreferences = preferences.getPreferencesSync(context, {name: this.name});}/*** 获取存储的字符串数组* @param context 上下文对象* @returns 字符串数组*/public async get(context: Context): Promise<Array<string>> {const pf = await preferences.getPreferences(context, this.name);const data = pf.getSync('my_str', []) as Array<string>;return data;}/*** 添加字符串到数组并保存* @param context 上下文对象* @param str 要添加的字符串*/public async put(context: Context, str: string) {const pf = await preferences.getPreferences(context, this.name);let data = pf.getSync('my_str', []) as Array<string>;data.push(str);pf.putSync('my_str', data);pf.flushSync();}
}/** 单例实例 */
let preferencesUtil: PreferencesUtil | undefined;/*** 获取PreferencesUtil单例* @returns 唯一实例*/
export function getPreferencesUtil(): PreferencesUtil {if (!preferencesUtil) {preferencesUtil = new PreferencesUtil();}return preferencesUtil;
}

以上是个人经验分享。

看完了,如果觉得有所收获,可以免费点个赞或收藏。

http://www.dtcms.com/a/388879.html

相关文章:

  • 常温超导新突破!NixCu-O7材料设计引领能源革命(续)
  • 常温超导新突破!NixCu-O7材料设计引领能源革命
  • C++,C#,Rust,Go,Java,Python,JavaScript的性能对比
  • 《从崩溃到精通:C++ 内存管理避坑指南,详解自定义类型 new/delete 调用构造 / 析构的关键逻辑》
  • 鸿蒙:父组件调用子组件的三种方案
  • AppTest邀请测试 -邀请用户
  • 从零开始的云计算生活——第六十五天,鹏程万里,虚拟化技术
  • Java 开发指南:将 PDF 转换为多种图片格式
  • 【C++革命】董翔箭头函数库(xiang_arrow):在main函数里定义函数的终极方案
  • Ubuntu显示No operation system found
  • 【深度学习新浪潮】音频大模型方面有哪些最新的研究进展?
  • 第3节 创建视频素材时间线到剪映(Coze扣子空间剪映小助手零基础教程)
  • Unifi AP 网络路由取消使用 无线 Meshing
  • 计算机网络基础(四) --- TCP/IP网络结构(网络层) (上)
  • AR巡检与区块链融合:工业智能化的新引擎
  • Product Hunt 每日热榜 | 2025-09-18
  • WPF 字符竖向排列的排版格式(直排)显示控件
  • 多色零件自动化分拣与追溯系统案例和项目落地全计划
  • 自动化面试常见问题(英文版)
  • Kettle Carte 服务实战:从作业提交到日志监控全流程自动化(附 Shell 脚本)
  • 【数字展厅】数字科技展厅是怎么建设沉浸式体验的?
  • 2025网安周|美创科技多地联动,共筑数据安全防线
  • 数字大健康:一场重塑未来的健康革命,正被科技重新定义
  • 手搓一个可以自动化对比yolo模型性能曲线的工具
  • 海图科技双撕裂检测装置:筑牢矿用皮带运输安全防线
  • 32、语言模型训练全流程:从数据到模型的工程化实现
  • 打造一款支持 Mermaid 与 ECharts 的 Markdown 编辑器:基于 Vditor 的实战指南
  • 《算法闯关指南:优选算法-双指针》--07三数之和,08四数之和
  • 华为显卡部署
  • Salesforce知识点:LWC(Lightning Web Components)面试题及答案