HarmonyOS 清理app缓存的方法?

如题:HarmonyOS 清理app缓存的方法?

阅读 534
1 个回答

当前没有清除缓存的接口,推荐下面:查询缓存用storageStatistics.getCurrentBundleStats()接口。

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

详细用法见下面的链接:

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

import { common } from '@kit.AbilityKit'
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';

function clearCache(context:common.UIAbilityContext) {
  let cacheDir = context.cacheDir
  fs.listFile(cacheDir).then((filenames) => {
    for (let i = 0;i < filenames.length; i++) {
      let dirPath = cacheDir + filenames[i] // 判断是否文件夹
      let isDirectory: boolean = false
      try {
        isDirectory = fs.statSync(dirPath).isDirectory()
      } catch (e) {
        console.log(e)
      }
      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);
        });
      }
    }
  })
}
logo
HarmonyOS
子站问答
访问
宣传栏