HarmonyOS 获取缓存大小,删除缓存,删除不干净的问题

let promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {
  storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
    if (err) {
      console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
      resolve(0);
    }
    else {
      console.info(`Invoke getCurrentBundleStats succeeded, appsize is ${bundleStats.appSize}`);
      // resolve(bundleStats.cacheSize - 6731540)
      resolve(bundleStats.cacheSize);
    }
  });
});
return promise;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

通过storageStatistics.getCurrentBundleStats获取的cacheSize,请问如何删掉storageStatistics.getCurrentBundleStats所获取出来的缓存?

HarmonyOS
2024-12-27 15:53:49
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

首先查询缓存用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.
分享
微博
QQ
微信
回复
2024-12-27 18:13:43
相关问题
如何删除preferences中缓存数据?
1157浏览 • 1回复 待解决
HarmonyOS 缓存无法清理干净
850浏览 • 1回复 待解决
HarmonyOS 音频播放缓存大小太大
838浏览 • 1回复 待解决
HarmonyOS 关于获取缓存与清除缓存
527浏览 • 1回复 待解决
如何获取缓存数据和清理缓存
1243浏览 • 1回复 待解决
HarmonyOS音频缓存问题
1322浏览 • 1回复 待解决
HarmonyOS 清理缓存问题
635浏览 • 1回复 待解决
HarmonyOS 图片缓存问题
691浏览 • 1回复 待解决
HarmonyOS 图片缓存问题
708浏览 • 1回复 待解决
HarmonyOS 本地缓存问题
1032浏览 • 0回复 待解决
HarmonyOS 本地缓存问题
953浏览 • 1回复 待解决
HarmonyOS 清除APP缓存问题
571浏览 • 1回复 待解决
HarmonyOS Web组件缓存问题
696浏览 • 1回复 待解决
HarmonyOS web清除缓存问题
893浏览 • 1回复 待解决
HarmonyOS 懒加载数据删除问题
1225浏览 • 1回复 待解决