HarmonyOS 如何获取应用缓存并清理?

如何在应用中获取当前应用缓存并进行清理,是否有对应api实现

阅读 453
1 个回答

查询缓存用storageStatistics.getCurrentBundleStats()接口,

清除文件缓存,需要调用context的cacheDir获取缓存,然后调用系统文件fs接口,判断是文件或者文件夹,再分别消除缓存。

详细用法见下面的链接:

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

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-fs-space-statistics-V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fs-V5\#fsrmdirsync

demo如下:

import { storageStatistics } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs';
import { Context } from '@kit.AbilityKit';
import { BusinessError } from '@ohos.base';

//获取缓存
getCacheSize() {
  storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => {
    if (error) {
      console.error("getCurrentBundleStats failed with error:" + JSON.stringify(error));
    } else {
      let cacheSize = parseFloat((bundleStats.cacheSize / (1024*1024)).toFixed(1))
      console.info('cacheSize:' + cacheSize);
    }
  })
}

//清理缓存
clearCache() {
  const context: Context = getContext(this);
  let cacheDir = context.cacheDir
  fs.listFile(cacheDir).then((filenames) => {
    for (let i = 0;i < filenames.length; i++) {
      let dirPath = cacheDir+filenames[i]
      try {
        // 判断是否文件夹
        let isDirectory = fs.statSync(dirPath).isDirectory()
        if (isDirectory) {
          fs.rmdirSync(dirPath)
        } else {
          fs.unlink(dirPath).then(() => {
            console.info('remove file succeed');
          }).catch((err: BusinessError) => {
            console.info("remove file failed with error message: " + err.message + ", error code: " + err.code);
          });
        }
      }catch (e) {
        console.log(e)
      }
    }
  })
}
logo
HarmonyOS
子站问答
访问
宣传栏