HarmonyOS鸿蒙Next中如何实现计数在app关闭冷启动后,重新启动还能得到原来的计数值

发布于 1周前 作者 zlyuanteng 来自 鸿蒙OS

HarmonyOS鸿蒙Next中如何实现计数在app关闭冷启动后,重新启动还能得到原来的计数值 请问下大佬们,如何实现计数在app关闭冷启动后,重新启动还能得到原来的计数值呀。

3 回复

【背景知识】

可以选择使用PersistenceV2来存储持久化的数据。PersistenceV2是应用程序中的可选单例对象。此对象的作用是持久化存储UI相关的数据,以确保这些属性在应用程序重新启动时的值与应用程序关闭时的值相同。

PersistenceV2提供状态变量持久化能力,开发者可以通过connect绑定同一个key,在状态变量变换和应用冷启动时,实现持久化能力。

【解决方案】

可以通过使用PersistenceV2和@local修饰的变量来实现变量的存储,下面提供一个示例:

import { PersistenceV2, Type } from '@kit.ArkUI';

@ObservedV2
class SampleClass {
  p1?: number = 0;
  p2?: number = 0;
}

@ObservedV2
class FatherSampleClass {
  @Type(SampleClass)
  @Trace f: SampleClass = new SampleClass();
}

@Entry
@ComponentV2
export struct TestPersistenceV2 {
  @Local v: FatherSampleClass = PersistenceV2.connect(FatherSampleClass, () => new FatherSampleClass())!;

  build() {
    Column() {
      Text(`ADD`)
        .fontSize(32)
        .onClick(() => {
          let sample = new SampleClass();
          sample.p1 = Date.now();
          sample.p2 = (this.v.f.p2 ?? 0) + 1;
          this.v.f = sample;
        })
      Text(`${JSON.stringify(this.v.f)}`)
        .fontSize(32)
    }
    .width("100%")
    .alignItems(HorizontalAlign.Center)
  }
}

【总结】

当想要保存变量或者类在冷启动的时候,还能获取到上次程序运行的值可以使用PersistenceV2来实现持久化储存UI状态。

更多关于HarmonyOS鸿蒙Next中如何实现计数在app关闭冷启动后,重新启动还能得到原来的计数值的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,要实现计数在App关闭冷启动后重新启动还能得到原来的计数值,可以使用PreferencesDataAbility进行数据持久化存储。

  1. 使用Preferences:
  • Preferences是鸿蒙提供的一种轻量级数据存储方式,适合存储简单的键值对数据。
  • 在App启动时,通过Preferences读取存储的计数值;在计数变化时,将新的计数值写入Preferences
  • 示例代码:
import preferences from '@ohos.data.preferences';

let preferences = await preferences.getPreferences(this.context, 'countData');
let count = await preferences.get('count', 0); // 读取计数值
await preferences.put('count', count + 1); // 更新计数值
await preferences.flush(); // 保存数据
  1. 使用DataAbility:
  • DataAbility是鸿蒙提供的一种数据共享机制,适合存储结构化数据。
  • 通过DataAbility将计数值存储在数据库中,App启动时从数据库中读取计数值。
  • 示例代码:
import featureAbility from '@ohos.ability.featureAbility';

let dataAbilityHelper = featureAbility.acquireDataAbilityHelper('dataability:///com.example.myapp.DataAbility');
let result = await dataAbilityHelper.query({}, ['count']);
let count = result[0].count; // 读取计数值
await dataAbilityHelper.update({ count: count + 1 }, {}); // 更新计数值

通过以上方法,可以在App冷启动后恢复之前的计数值。

在HarmonyOS鸿蒙Next中,可以使用PreferencesDatabase来持久化保存计数值。使用Preferences的步骤如下:

  1. EntryAbilityonCreate方法中初始化Preferences

    private Preferences preferences;
    [@Override](/user/Override)
    public void onCreate() {
        preferences = Preferences.getPreferences(this);
    }
  2. 在需要保存计数值时,使用putInt方法保存:

    preferences.putInt("count", count);
    preferences.flush();
  3. onStart方法中,使用getInt方法读取计数值:

    int count = preferences.getInt("count", 0);

这样,即使应用冷启动后,也能获取到之前的计数值。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!