import { preferences } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';


class DataFreferencesUtil {
  private dataPreferences: preferences.Preferences | null = null;

  /**
   * 初始化用户首选项
   * @param context
   * @param dataFerName
   */
  initData(context: Context, dataFerName: string) {

    let options: preferences.Options = { name: dataFerName };
    this.dataPreferences = preferences.getPreferencesSync(context, options);
    let observer = (key: string) => {
      console.info('hhh' + key)
      // this.flushData()

    }
    this.dataPreferences.on('change', observer);
    console.info('初始化完成')
  }

  /**
   * 插入数据
   * @param key
   * @param value
   */
  insertData(key: string, value?: string) {
    if (this.dataPreferences) {
      if (this.dataPreferences.hasSync(key)) {
        console.log(`插入的 '${key}' 已存在.    --3`);
      } else {
        console.log(`插入的 '${key}' 不存在.---3`);
        // 此处以此键值对不存在时写入数据为例
        this.dataPreferences.putSync(key, value || 'default');
        // 当字符串有特殊字符时,需要将字符串转为Uint8Array类型再存储 theme
        // let uInt8Array1 = new util.TextEncoder().encodeInto("~!@#¥%……&*()——+?");
        // this.dataPreferences.put('uInt8', uInt8Array1);
        this.flushData()
      }
    }
  }

  insertData2(key:string,value:string) {
    if (this.dataPreferences) {
      this.dataPreferences.put(key,value, (err: BusinessError) => {
        if (err) {
          console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
          return;
        }
      })
      this.flushData()
    }

  }

  /**
   * 读取数据
   * @param key
   * @param value
   */
  readData(key: string, value?: string) {
    if (this.dataPreferences) {
      // let val = this.dataPreferences.getSync(key, value || 'default');
      let val = this.dataPreferences.getSync(key, value || 'default');
      console.info(`The ${key} value is ` + val || 'default');
      // 当获取的值为带有特殊字符的字符串时,需要将获取到的Uint8Array转换为字符串
      // let uInt8Array2: preferences.ValueType = this.dataPreferences.getSync('uInt8', new Uint8Array(0));
      // let textDecoder = util.TextDecoder.create('utf-8');
      // val = textDecoder.decodeToString(uInt8Array2 as Uint8Array);
      // console.info("The 'uInt8' value is " + val);
      return val
    } else {
      return 'default'
    }
  }

  /**
   * 删除数据
   * @param key
   */
  deleteData(key: string) {
    if (this.dataPreferences) {
      this.dataPreferences.delete(key);
      this.flushData()
    }
  }

  /**
   * 数据持久化
   */
  flushData() {
    if (this.dataPreferences) {
      this.dataPreferences.flush((err: BusinessError) => {
        if (err) {
          console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
          return;
        }
        console.info('数据已经持久化.');
      })
    }
  }
}

const dataFreferencesUtil = new DataFreferencesUtil()

export { dataFreferencesUtil }

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐