HarmonyOS app中清理缓存的功能,包括Web的缓存,一般都需要清理哪些文件夹下的缓存,有没有对应的示例代码?

HarmonyOS
2024-12-17 13:03:59
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Excelsior_abit

app清理缓存:

查询缓存用storageStatistics.getCurrentBundleStats()接口,清除文件缓存,需要调用context的cacheDir获取缓存,然后调用系统文件fs接口,判断是文件或者文件夹,再分别消除缓存。示例代码:

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)
      }
    }
  })
}
  • 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.
  • 39.
  • 40.
  • 41.
  • 42.

参考链接: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

web清除缓存可以参考如下链接中的demo:

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

分享
微博
QQ
微信
回复
2024-12-17 15:26:12
相关问题
DevEco有没有清理调试应用缓存功能
5027浏览 • 1回复 待解决
HarmonyOS 清理app缓存方法
692浏览 • 1回复 待解决
HarmonyOS 如何清理web缓存
438浏览 • 1回复 待解决
HarmonyOS web 清理缓存
591浏览 • 1回复 待解决
HarmonyOS web清理缓存
890浏览 • 1回复 待解决
HarmonyOS 如何清理 web 缓存
563浏览 • 1回复 待解决
HarmonyOS 清理缓存问题
650浏览 • 1回复 待解决
如何获取缓存数据和清理缓存
1243浏览 • 1回复 待解决
HarmonyOS 如何清理Image磁盘缓存
839浏览 • 1回复 待解决
HarmonyOS ArkWeb如何清理缓存
518浏览 • 1回复 待解决
HarmonyOS 关于应用清理缓存
1152浏览 • 1回复 待解决
HarmonyOS 缓存无法清理干净
853浏览 • 1回复 待解决
HarmonyOS 应用缓存清理不彻底
642浏览 • 1回复 待解决
用file api清理缓存目录
1374浏览 • 1回复 待解决
HarmonyOS 如何获取应用缓存清理
611浏览 • 1回复 待解决
HarmonyOS APP有没有清除缓存接口
1294浏览 • 1回复 待解决