实现效果
默认字体颜色为绿色,修改颜色后,保存设置为橙色。
再次打开后,获取本地存储的数据,设置字体颜色为橙色。
实现思路
封装用户首选项(@ohos.data.preferences)工具类。
通过用户首选项的应用持久化轻量级数据的能力,保存设置。
代码实现
封装PreferencesUtils
导入模块:
import preferences from '@ohos.data.preferences';
工具类结构定义:
class PreferencesUtils {
preMap: Map<string, preferences.Preferences> = new Map()
// 加载数据
async loadPreferences() {
// ...
}
// 新增
async putPreferencesValue() {
// ...
}
// 获取
async getPreferencesValue() {
// ...
}
// 删除
async deletePreferencesValue() {
// ...
}
}
实现加载方法:
async loadPreferences(context, name: string) {
try {
const pref = await preferences.getPreferences(context, name)
this.preMap.set(name, pref)
console.log(`加载preferences[${name}]成功`)
} catch (e) {
console.log(`加载preferences[${name}]失败`, JSON.stringify(e))
}
}
实现新增方法:
async putPreferencesValue(name: string, key: string, value: preferences.ValueType)
{
if (!this.preMap.has(name)) {
console.log(`preferences[${name}]尚未初始化`)
return
}
try {
const pref = this.preMap.get(name)
await pref.put(key, value)
await pref.flush()
console.log(`preferences[${name}]保存成功`)
} catch (e) {
console.log(`preferences[${name}]保存失败`, JSON.stringify(e))
}
}
实现获取方法:
async getPreferencesValue(name: string, key: string, defaultValue: preferences.ValueType) {
if (!this.preMap.has(name)) {
console.log(`preferences[${name}]尚未初始化`)
return defaultValue
}
try {
const pref = this.preMap.get(name)
const value = await pref.get(key, defaultValue)
console.log(`preferences[${name}].${key}=${value}读取成功`)
return value
} catch (e) {
console.log(`preferences[${name}]读取失败`, JSON.stringify(e))
}
}
实现删除方法:
async deletePreferencesValue(name: string, key: string) {
if (!this.preMap.has(name)) {
console.log(`preferences[${name}]尚未初始化`)
return
}
try {
const pref = this.preMap.get(name)
await pref.delete(key)
console.log(`preferences[${name}].${key}删除成功`)
} catch (e) {
console.log(`preferences[${name}]删除失败`, JSON.stringify(e))
}
}
导出:
const preferenceUtils = new PreferencesUtils()
export default preferenceUtils as PreferencesUtils
初始化PreferencesUtils
在EntryAbility中初始化:
// 引入PreferencesUtils
import PreferencesUtils from '../utils/PreferencesUtil'
// 在生命周期中初始化PreferencesUtils
onCreate(want, launchParam) {
PreferencesUtils.loadPreferences(this.context, constants.PREFERENCE_KEY)
}
保存数据
改变颜色时保存数据:
await PreferencesUtils.putPreferencesValue('my_app', 'font_color', this.fontColor)
获取数据
在页面生命周期函数中获取数据:
this.fontColor = await PreferencesUtils.getPreferencesValue('my_app', 'font_color', '#00e09b')
完结散花
如发现文章内容有任何问题,请提出您的宝贵意见予以指正,感谢您的阅读。