HarmonyOS如何添加首选项功能

目录

什么是用户首选项?

用户首选项运作机制

用户首选项的使用场景

如何使用用户首选项

用户首选项的逻辑代码

用户首选项配置

context参数

在页面中加载数据

案例:使用用户首选项控制首页弹窗

在UIAbility加载弹窗

获取上下文context

传递参数,加载首选项

保存首选项

结语


什么是用户首选项?

用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。当用户希望有一个全局唯一存储的地方,可以采用用户首选项来进行存储。Preferences会将该数据缓存在内存中,当用户读取的时候,能够快速从内存中获取数据,当需要持久化时可以使用flush接口将内存中的数据写入持久化文件中。

用户首选项运作机制

用户首选项的使用场景

Preferences会随着存放的数据量越多而导致应用占用的内存越大,因此,Preferences不适合存放过多的数据,适用的场景一般为应用保存用户的个性化设置(字体大小,是否开启夜间模式)等。

如何使用用户首选项

在ets目录下新建一个common目录,在common目录下新建一个工具目录utils,utils目录下新建一个preferences.ts文件用来编写用户首选项的逻辑代码

用户首选项的逻辑代码

import preferences from '@ohos.data.preferences';
import { CommonConstants } from '../constants/CommonConstants';
import Logger from './Logger';

class PreferenceUtil{
  private pref: preferences.Preferences

  async loadPreference(context){
    try { // 加载preferences
      this.pref = await preferences.getPreferences(context, CommonConstants.H_STORE)
      Logger.debug(`加载Preferences[${CommonConstants.H_STORE}]成功`)
    } catch (e) {
      Logger.debug(`加载Preferences[${CommonConstants.H_STORE}]失败`, JSON.stringify(e))
    }
  }

  async putPreferenceValue(key: string, value: preferences.ValueType){
    if (!this.pref) {
      Logger.debug(`Preferences[${CommonConstants.H_STORE}]尚未初始化!`)
      return
    }
    try {
      // 写入数据
      await this.pref.put(key, value)
      // 刷盘
      await this.pref.flush()
      Logger.debug(`保存Preferences[${key} = ${value}]成功`)
    } catch (e) {
      Logger.debug(`保存Preferences[${key} = ${value}]失败`, JSON.stringify(e))
    }
  }

  async getPreferenceValue(key: string, defaultValue: preferences.ValueType){
    if (!this.pref) {
      Logger.debug(`Preferences[${CommonConstants.H_STORE}]尚未初始化!`)
      return
    }
    try {
      // 读数据
      let value = await this.pref.get(key, defaultValue)
      Logger.debug(`读取Preferences[${key} = ${value}]成功`)
      return value
    } catch (e) {
      Logger.debug(`读取Preferences[${key}]失败`, JSON.stringify(e))
    }
  }
}

const preferenceUtil = new PreferenceUtil()

export default preferenceUtil as PreferenceUtil

用户首选项配置

在EntryAbility的生命周期钩子onCreate中加载用户首选项,使用PreferenceUtil之前先导包否则会报错,这里使用的loadPreference就是逻辑代码中的用来加载首选项的方法,把context作为参数传过去

onCreate(want, launchParam) {
    //加载用户首选项
    PreferenceUtil.loadPreference(this.context)
  }

context参数

context参数表示的是当前 UIAbility 的上下文

context = getContext(this) as common.UIAbilityContext

getContext(this) 是一个获取当前 Ability(能力)上下文的方法

在页面中加载数据

先在UIAbility中导包,然后在UIAbility的aboutToAppear(页面一加载就会自动调用的函数)方法中调用PreferenseUtil中的getPerenceValue方法拿到首选项里的参数,用来获取之前保存的数据,拿到数据后就可以判断你的下一步要执行的操作了

案例:使用用户首选项控制首页弹窗

 弹窗代码:


import { CommonConstants } from '../../common/constants/CommonConstants'

@CustomDialog
export default struct UserPrivacyDialog {
  controller: CustomDialogController
  confirm: () => void
  cancel: ()=> void
  build() {
    Column({space:CommonConstants.SPACE_10}){
      //标题
      Text($r('app.string.user_privacy_title'))
        .fontSize(20)
        .fontWeight(CommonConstants.FONT_WEIGHT_700)
      //内容
      Text($r('app.string.user_privacy_content'))
      //按钮
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button($r('app.string.agree_label'))
          .width(150)
          .backgroundColor($r('app.color.primary_color'))
          .onClick(() => {
            this.confirm()
            this.controller.close()
          })
        Button($r('app.string.refuse_label'))
          .width(150)
          .backgroundColor($r('app.color.lightest_primary_color'))
          .fontColor($r('app.color.light_gray'))
          .onClick(() => {
            this.cancel()
            this.controller.close()
          })
      }
      .margin({left:5 , right: 5 ,bottom:10})

    }
    .width('100%')
    .padding(10)

  }
}

这个弹窗是为了让用户进入该app之前,同意一些app相关的协议,以便于遵守app的使用规则

注:

这里面的一些图片和字体颜色规格都是我本地文件夹下自定义的,想使用的小伙伴ctrl+c后可以手动改一下才能正常运行

在UIAbility加载弹窗

在WelcomePages页面里要声明弹窗组件

controller: CustomDialogController = new CustomDialogController({
    builder: UserPrivacyDialog({
      confirm: () => this.onConfirm(),
      cancel: () => this.exitApp()
    })
  })

注:confirm和cancel是弹窗组件中的方法,用来执行同意和不同意时的逻辑

获取上下文context

context用来作为用户首选项的参数传递 

context = getContext(this) as common.UIAbilityContext

再定义一个key作为传递的参数,意为用户'隐私协议'

const PREF_KEY= 'userPrivacyKey'

传递参数,加载首选项

async aboutToAppear(){
    //加载首选项
    let isAgree = await PreferenceUtil.getPreferenceValue(PREF_KEY,false)
    //判断是否同意
    if(isAgree){
      //同意,跳转
      this.jumpToIndex()
    }else {
      //不同意,弹窗
      this.controller.open()
    }
  }

注:这里的jumpToIndex方法是用来实现跳转另一个页面,你可以自己新建一个页面充当一下

逻辑:在aboutToAppear方法中,如果拿到的isAgree为true,则直接跳转至目标页(应用中的下一个页面),若拿到的isAgree为false,则调用this.controller.open()方法展示弹窗

保存首选项

onConfirm方法:是在弹窗组件中定义的一个点击同意按钮时执行的操作

onConfirm(){
    //保存首选项
    PreferenceUtil.putPreferenceValue(PREF_KEY,true)
    //跳转首页
    this.jumpToIndex()
  }

在onConfirm方法中调用putPreferenceValue方法,点击同意按钮就存一个true进去,在下次加载用户首选项时,拿到的是true则表示已同意作者某些自定义的内容,就不再加载弹窗

结语

以上就是本文章的全部内容,没有太多写博客的经验,如有错误,非常愿意领教大佬们的指正,我会努力进步,以后也会写出更好的博客,作者也是一位热爱学习鸿蒙的爱好者,在努力学习中,与喜欢学习鸿蒙的小伙伴一起进步!加油!

  • 25
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值