鸿蒙首选项数据持久化

1. ets/common/util/PreferencesUtils.ets

import { common } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';

class PreferencesUtil {
  prefMap: Map<string, preferences.Preferences> = new Map()

  /*加载首选项*/
  loadPreference(context: common.UIAbilityContext, name: string) {
    try {
      let options: preferences.Options = { name: name };
      let pref = preferences.getPreferencesSync(context, options)
      this.prefMap.set(name, pref)
    } catch (e) {
      console.error('testTag', `加载首选项${name}失败`, JSON.stringify(e))
    }
  }

  /*写入首选项*/
  putPreferences(name: string, key: string, value: string) {
    if (!this.prefMap.has(name)) {
      console.error('testTag', `首选项${name}尚未初始化1`)
      return
    }
    this.prefMap.get(name)?.putSync(key, value)
    this.prefMap.get(name)?.flush()
  }

  /*读取首选项*/
  readPreferences(name: string, key: string, defaultValue: string) {
    if (!this.prefMap.has(name)) {
      console.error('testTag', `首选项${name}尚未初始化2`)
      return ''
    }
    return this.prefMap.get(name)?.getSync(key, defaultValue)
  }
}

const preferencesUtil = new PreferencesUtil()

export default preferencesUtil as PreferencesUtil

2. entry/src/main/ets/entryability/EntryAbility.ets   onWindowStageCreate 方法添加

/*加载首选项*/
preferencesUtil.loadPreference(this.context,'myStore')

3. entry/src/main/ets/pages/Index.ets 读取首选项数据

aboutToAppear(): void {
  this.flag = String(preferencesUtil.readPreferences('myStore', 'flag', '-1'))
  console.info('testTag',this.flag)
}

 

posted @ 2024-10-10 16:39  龍飛鳯舞  阅读(15)  评论(0编辑  收藏  举报