iimsimsiHarmonyOS 获取和清理缓存的API方法

开发APP过程中,如何实现获取缓存和清理缓存(如图),具体的API和实现方法

iimsimsiHarmonyOS  获取和清理缓存的API方法 -鸿蒙开发者社区

HarmonyOS
2024-08-02 14:58:53
791浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
北风_小浦

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

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

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) 
      } 
    } 
  }) 
}
  • 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

分享
微博
QQ
微信
回复
2024-08-02 20:17:09


相关问题
如何获取缓存数据清理缓存
1189浏览 • 1回复 待解决
HarmonyOS 清理app缓存方法
627浏览 • 1回复 待解决
用file api清理缓存目录
1302浏览 • 1回复 待解决
HarmonyOS 如何获取应用缓存清理
546浏览 • 1回复 待解决
HarmonyOS 清理缓存问题
593浏览 • 1回复 待解决
HarmonyOS web 清理缓存
521浏览 • 1回复 待解决
HarmonyOS web清理缓存
774浏览 • 1回复 待解决
HarmonyOS 如何清理web缓存
379浏览 • 1回复 待解决
HarmonyOS 缓存无法清理干净
785浏览 • 1回复 待解决
HarmonyOS 如何清理 web 缓存
505浏览 • 1回复 待解决
HarmonyOS 关于应用清理缓存
1039浏览 • 1回复 待解决
HarmonyOS ArkWeb如何清理缓存
468浏览 • 1回复 待解决
HarmonyOS 如何清理Image磁盘缓存
732浏览 • 1回复 待解决
HarmonyOS 应用缓存清理不彻底
581浏览 • 1回复 待解决
DevEco有没有清理调试应用缓存功能
4923浏览 • 1回复 待解决
HarmonyOS 是否有清理urlcache方法
1023浏览 • 1回复 待解决