HarmonyOS获取、清除app缓存

HarmonyOS的app缓存清理管理类


import { BusinessError } from '@ohos.base';
import { Logger } from '@ohos/httpclient';
import { fileIo } from '@kit.CoreFileKit';
import web_webview from '@ohos.web.webview'
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';

//缓存管理工具
export class TBXCacheManager {
  private context = getContext(this) as common.UIAbilityContext
  private cacheDic = this.context.cacheDir
  private static instance: TBXCacheManager;
  private constructor() {
  }

  public static getInstance(): TBXCacheManager {
    if (!TBXCacheManager.instance) {
      TBXCacheManager.instance = new TBXCacheManager()
    }
    return TBXCacheManager.instance;
  }

  // 定义一个异步函数来递归获取目录内所有文件的总大小
  async getDirectorySizeAsync(directoryPath: string): Promise<number> {
    let totalSize = 0;
    try {
      //获取路径下的所有子目录
      const files = fileIo.listFileSync(directoryPath);
      for (const file of files) {
        const filePath = `${directoryPath}/${file}`;
        const stats = await fileIo.stat(filePath);
        if (stats.isDirectory()) {
          //如果是文件夹,那么就继续遍历
          totalSize += await this.getDirectorySizeAsync(filePath);
        } else {
          //如果是文件,就直接获取文件大小
          totalSize += await this.getFileSizeAsync(filePath);
        }
      }
    } catch (error) {
      console.error(`Error listing files in ${directoryPath}:`, error);
    }
    return totalSize;
  }

  // 定义一个异步函数来处理文件大小的累加
  async getFileSizeAsync(filePath: string): Promise<number> {
    try {
      const stats = await fileIo.stat(filePath);
      return stats.isFile() ? stats.size : 0;
    } catch (error) {
      console.error(`Error getting size of ${filePath}:`, error);
      return 0;
    }
  }

  /*获取app缓存大小*/
  async getAppCacheSize(): Promise<number> {
    let cacehSize = await this.getDirectorySizeAsync(this.cacheDic)
    return Math.round(cacehSize/(1024*1024) * 10)/10
  }

  /*清除APP所有缓存信息*/
  removeAppAllCache(removeHandler: () => void) {
    //清理web缓存
    this.removeWebCache()
    this.clearCache(removeHandler)
  }

  /*清理普通缓存*/
  private clearCache(removeHandler: () => void) {
    fileIo.rmdir(this.cacheDic, async (err: BusinessError) => {
      if (err) {
        Logger.debug('remove app cache faild' + err.message)
      } else {
        console.debug('clear success')
      }
      removeHandler()
    })
  }

  /*清理web的缓存*/
  private removeWebCache() {
    web_webview.WebCookieManager.clearAllCookiesSync()
    web_webview.WebStorage.deleteAllData()
  }
}

使用的时候直接调用:
获取app缓存大小:

        let cacheSize = await TBXCacheManager.getInstance().getAppCacheSize()
        cacheModel.subtitle = String(cacheSize) + 'M'

清理app缓存:

     TBXCacheManager.getInstance().removeAppAllCache( async () => {
      //处理后续逻辑,比如更改UI上缓存大小显示
    })

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容