文档管理中心
我的
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
行业解决方案行业分类公共关键技术方案关键场景示例应用缓存清除

应用缓存清除

场景介绍

清除应用缓存是各类应用中的高频使用场景之一,本示例基于@ohos.file.fs实现缓存清理。

效果预览

实现思路

  1. 通过getHostContext()和application.createModuleContext()获取以下四个文件缓存路径,存储至paths数组。
    • /data/storage/el1/base/cache;
    • /data/storage/el1/base/haps/entry/cache;
    • /data/storage/el2/base/cache;
    • /data/storage/el2/base/haps/entry/cache;
    收起
    自动换行
    深色代码主题
    复制
    1. moduleContext = await application.createModuleContext(this.context, 'entry')
    2. // 缓存路径/data/storage/el2/base/cache
    3. paths.push(moduleContext.cacheDir)
    4. // 缓存路径/data/storage/el2/base/haps/entry/cache
    5. paths.push(this.context.cacheDir)
    6. // 缓存路径/data/storage/el1/base/cache
    7. moduleContext.area = contextConstant.AreaMode.EL1
    8. paths.push(moduleContext.cacheDir)
    9. // 缓存路径/data/storage/el1/base/haps/entry/cache
    10. context.area = contextConstant.AreaMode.EL1
    11. paths.push(this.context.cacheDir)
    12. // 获取完需要清理的路径之后,moduleContext.area和context.area需要切换回应用原本的加密分区,否则可能会影响其他业务功能。
  2. 遍历paths数组,调用deleteFile()清除缓存文件。
    收起
    自动换行
    深色代码主题
    复制
    1. clearAllCache() {
    2. this.paths.forEach((cacheDir) => {
    3. hilog.info(0x0000, 'CacheClean', cacheDir)
    4. this.deleteFile(cacheDir)
    5. })
    6. }
    7. deleteFile(cacheDir: string) {
    8. fs.listFile(cacheDir)
    9. .then((filenames) => {
    10. filenames.forEach((name) => {
    11. let dirPath = cacheDir + '/' + name
    12. hilog.info(0x0000, 'CacheClean', dirPath)
    13. // 判断是否为文件夹
    14. let isDirectory: boolean = false
    15. try {
    16. isDirectory = fs
    17. .statSync(dirPath)
    18. .isDirectory()
    19. } catch (e) {
    20. hilog.error(0x0000, 'CacheClean', JSON.stringify(e))
    21. }
    22. if (isDirectory) {
    23. fs.rmdirSync(dirPath)
    24. } else {
    25. fs.unlink(dirPath)
    26. .then(() => {
    27. hilog.info(0x0000, 'CacheClean', 'Remove files successfully')
    28. })
    29. .catch((err: Error) => {
    30. let log = `Failed to remove files with error message: ${err.message}`
    31. hilog.error(0x0000, 'CacheClean', log)
    32. })
    33. }
    34. })
    35. })
    36. }

约束与限制

  • 本示例支持API Version 20 Release及以上版本。
  • 本示例支持HarmonyOS 6.0.0 Release SDK及以上版本。
  • 本示例需要使用DevEco Studio 6.0.0 Release及以上版本进行编译运行。

工程目录

收起
自动换行
深色代码主题
复制
  1. ├──entry/src/main/ets
  2. │ ├──entryability
  3. │ │ └──EntryAbility.ets
  4. │ ├──model
  5. │ │ └──SettingModel.ets // 设置列表
  6. │ └──pages
  7. │ └──CacheClean.ets // 主页面
  8. └──entry/src/main/resources // 应用资源目录