缓存问题?

一般应用如何清除缓存,目前通过@ohos.file.fs的rmdir清除缓存文件后发现在应用未重启的情况下Image的缓存失效了

阅读 569
1 个回答

参考如下代码:

import common from '@ohos.app.ability.common';
import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Page_Context {
  private context = getContext(this) as common.UIAbilityContext;

  build() {
    Column() {
      Image("xxx").width("100vp").height("100vp")
      Image("xxx").width("100vp").height("100vp")
      Image("xxx").width("100vp").height("100vp")
      Image("xxx").width("100vp").height("100vp")

      Button("获取上下文目录")
        .onClick(() => {
          // 获取应用文件路径
          console.info("cacheDir:", this.context.cacheDir);
        })

      Button("获取当前应用的存储空间大小")
        .onClick(() => {
          storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
            if (err) {
              console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
            } else {
              console.info(`Invoke getCurrentBundleStats succeeded, appsize is ${bundleStats.appSize} Byte`);
              console.info(`Invoke getCurrentBundleStats succeeded, cacheSize is ${bundleStats.cacheSize} Byte`);
              console.info(`Invoke getCurrentBundleStats succeeded, dataSize is ${bundleStats.dataSize} Byte`);
            }
          });
        })
    }
  }
}
Button("清除缓存")
  .onClick(()=>{
    let cacheDir = this.context.cacheDir;
    console.info("cacheDir:", cacheDir);
    fs.listFile(cacheDir).then((filenames: Array<string>) => {
      console.info("listFile succeed");
      for (let i = 0; i < filenames.length; i++) {
        console.info("fileName: %s", filenames[i]);
        fs.unlink(`${cacheDir}/${filenames[i]}`)
      }
    }).catch((err: BusinessError) => {
      console.error("list file failed with error message: " + err.message + ", error code: " + err.code);
    });
  })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进