鴻蒙首選項資料持久化

龍飛鳯舞發表於2024-10-10

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)
}

相關文章