缓存清除解决方案:基于 HarmonyOS 文件管理的应用缓存清理项目

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

分支1Tags0

缓存清除解决方案

介绍

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

效果预览

环境准备

  • 本示例基于DevEco Studio 26.0.0 Release版本进行编译运行。
  • 本示例基于API Version 26 Release版本进行开发与验证。

实现思路

  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
moduleContext = await application.createModuleContext(this.context, 'entry');

// Cache path: /data/storage/el2/base/cache
hilog.info(0x0000, 'CacheClean', `moduleContext + el2: ${moduleContext.cacheDir}`);
// Cache path: /data/storage/el2/base/haps/entry/cache
hilog.info(0x0000, 'CacheClean', `UIAbilityContext + el2: ${this.context.cacheDir}`);

paths.push(moduleContext.cacheDir);
paths.push(this.context.cacheDir);

// Cache path: /data/storage/el1/base/cache
moduleContext.area = contextConstant.AreaMode.EL1;
hilog.info(0x0000, 'CacheClean', `moduleContext + el1: ${moduleContext.cacheDir}`);
// Cache path: /data/storage/el1/base/haps/entry/cache
this.context.area = contextConstant.AreaMode.EL1;
hilog.info(0x0000, 'CacheClean', `UIAbilityContext + el1: ${this.context.cacheDir}`);

paths.push(moduleContext.cacheDir);
paths.push(this.context.cacheDir);
  1. 遍历paths数组,调用deleteFile()清除缓存文件。
deleteFile(cacheDir: string) {
fs.listFile(cacheDir)
  .then((filenames) => {
    filenames.forEach((name) => {
      let dirPath = cacheDir + '/' + name;
      hilog.info(0x0000, 'CacheClean', dirPath);
      // Check whether this is a directory
      let isDirectory: boolean = false;
      try {
        isDirectory = fs
          .statSync(dirPath)
          .isDirectory();
      } catch (e) {
        hilog.error(0x0000, 'CacheClean', JSON.stringify(e));
      }
      if (isDirectory) {
        fs.rmdirSync(dirPath);
      } else {
        fs.unlink(dirPath)
          .then(() => {
            hilog.info(0x0000, 'CacheClean', 'Remove files successfully');
          })
          .catch((err: Error) => {
            let log = `Failed to remove files with error message: ${err.message}`;
            hilog.error(0x0000, 'CacheClean', log);
          });
      }
    });
  });
}

// Clear all cache
clearAllCache() {
this.paths.forEach((cacheDir) => {
  hilog.info(0x0000, 'CacheClean', cacheDir);
  this.deleteFile(cacheDir);
});
}

工程目录

├──entry/src/main/ets 
│  ├──entryability
│  │  └──EntryAbility.ets
│  ├──model
│  │  └──SettingModel.ets            // Settings list
│  └──pages
│     └──CacheClean.ets              // Main page
└──entry/src/main/resources          // Application resources

参考文档

@ohos.file.fs (文件管理)

Class(UIContext)

@ohos.app.ability.application(应用工具类)

项目介绍

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

定制我的领域