HarmonyOS 官方的检查缓存和清理缓存的API

HarmonyOS
2024-12-23 15:08:22
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
aquaa

没有直接的API清理应用数据,但可以参考以下应用空间统计API:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-storage-statistics-V5

首先查询缓存用storageStatistics.getCurrentBundleStats()接口,再清除文件缓存,需要调用context的cacheDir获取缓存,然后调用系统文件fs接口,判断是文件或者文件夹,再清除缓存。

可以参考以下案例,本地测试删除缓存后,getCurrentBundleStats返回正常。

import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import storageStatistics from '@ohos.file.storageStatistics';
import fs from '@ohos.file.fs';
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.cacheDir;
@Entry
@Component
struct Index {

  @State message: string = 'Hello World';
  // let context = getContext(this) as common.UIAbilityContext;
  aboutToAppear(): void {
    //fs清除缓存
    fs.rmdirSync(filesDir);
    //获取空间
    storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => {
      if (error) {
        console.error("getCurrentBundleStats failed with error:" + JSON.stringify(error));
      } else {
        // do something
        console.info("8899getCurrentBundleStats successfully:" + JSON.stringify(bundleStats));
      }
    });
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')

  }
}
  • 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.

清除不了的数据可能包括首选项和web 首选项和Web组件里的缓存,

首选项清除请参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5#clear

首选项清除操作中,请根据自己的需要使用delete或者clear,

具体如下 delete:从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化,

使用callback异步回调 clear:清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,

使用callback异步回调 web清除缓存请参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/web-cookie-and-data-storage-mgmt-V5

分享
微博
QQ
微信
回复
2024-12-23 19:29:49
相关问题
如何获取缓存数据清理缓存
1255浏览 • 1回复 待解决
用file api清理缓存目录
1380浏览 • 1回复 待解决
HarmonyOS 清理app缓存方法
711浏览 • 1回复 待解决
HarmonyOS 如何清理web缓存
448浏览 • 1回复 待解决
HarmonyOS 清理缓存问题
659浏览 • 1回复 待解决
HarmonyOS web清理缓存
906浏览 • 1回复 待解决
HarmonyOS web 清理缓存
599浏览 • 1回复 待解决
HarmonyOS 如何清理Image磁盘缓存
850浏览 • 1回复 待解决
HarmonyOS ArkWeb如何清理缓存
530浏览 • 1回复 待解决
HarmonyOS 关于应用清理缓存
1162浏览 • 1回复 待解决
HarmonyOS 缓存无法清理干净
863浏览 • 1回复 待解决
HarmonyOS 如何清理 web 缓存
570浏览 • 1回复 待解决
HarmonyOS 应用缓存清理不彻底
654浏览 • 1回复 待解决
HarmonyOS 如何获取应用缓存清理
618浏览 • 1回复 待解决
DevEco有没有清理调试应用缓存功能
5034浏览 • 1回复 待解决
本地缓存分布式缓存有什么不同?
3553浏览 • 1回复 待解决