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

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

Branch1Tags0

Cache clearing solution

Introduction

Cache clearing solution is one of the most frequently used scenarios in various applications. This sample implements cache cleaning based on @ohos.file.fs.

Effect Preview

Environment Preparation

  • This sample is compiled and run based on DevEco Studio 26.0.0 Release.
  • This sample is developed and verified based on API Version 26 Release.

Implementation Approach

  1. Obtain the following four file cache paths via getHostContext() and application.createModuleContext(), and store them in a paths array.
  • /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. Iterate through the paths array and call deleteFile() to clear cache files.
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);
});
}

Project Directory

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

References

@ohos.file.fs (File Management)

Class(UIContext)

@ohos.app.ability.application (Application Utility Class)

Introduction

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

Customize your domain