HarmonyOS 首选项回调失效

用首选项订阅了一个key,这个key在前几次能收到回调,在模块切换后就无法收到回调。

HarmonyOS
2024-12-25 10:47:02
964浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

在多har包的情况,建议使用sendablePreferences,参考示例如下:

import { Context } from '@kit.AbilityKit';
import { sendablePreferences } from '@kit.ArkData';
import { lang } from '@kit.ArkTS';

export class PreferenceUtil {
  private pref: sendablePreferences.Preferences | undefined = undefined
  private static instance: PreferenceUtil;

  public static getInstance(): PreferenceUtil {
    if (PreferenceUtil.instance == null) {
      PreferenceUtil.instance = new PreferenceUtil();
      console.debug('PreferenceUtil getInstance  new  ')
    }
    return PreferenceUtil.instance;
  }

  loadPreference(context: Context, storeName: string) {
    try { // 加载preferences
      this.pref = sendablePreferences.getPreferencesSync(context, { name: storeName })
      console.debug(`加载Preferences成功`)
    } catch (e) {
      console.info(`加载Preferences失败`, JSON.stringify(e))
    }
  }

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

  async getPreferenceValue(key: string, defaultValue: lang.ISendable) {
    if (!this.pref) {
      console.debug(`Preferences 尚未初始化!`)
      return
    }
    try {
      // 读数据
      let value = this.pref.getSync(key, defaultValue)
      console.debug(`读取Preferences[${key} = ${value}]成功`)
      return value
    } catch (e) {
      console.debug(`读取Preferences[${key}]失败`, JSON.stringify(e))
      return
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.

参考文档如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-sendablepreferences-V5

分享
微博
QQ
微信
回复
2024-12-25 13:43:13


相关问题
HarmonyOS 首选项示例
728浏览 • 1回复 待解决
首选项preferences相关
838浏览 • 1回复 待解决
HarmonyOS TaskPool使用首选项报错
1345浏览 • 1回复 待解决
HarmonyOS 首选项报错数据报错
832浏览 • 1回复 待解决
HarmonyOS 创建首选项报错code:15500000
964浏览 • 1回复 待解决
HarmonyOS 获取首选项取值的方式
1005浏览 • 1回复 待解决
HarmonyOS 首选项超长string存储失败
791浏览 • 1回复 待解决
首选项存储问题,为什么会报错?
1115浏览 • 1回复 待解决
HarmonyOS 模拟器使用首选项能力异常
825浏览 • 1回复 待解决
HarmonyOS 用户首选项是线程安全的吗
1075浏览 • 1回复 待解决
首选项获取实例,实例是否为单例
2660浏览 • 1回复 待解决
错误码15500000(首选项)如何处理?
2177浏览 • 1回复 待解决