前言:鸿蒙实现 APP 清除缓存功能
import { fileIo, storageStatistics } from '@kit.CoreFileKit'; import { CacheInfo } from '../ble/module/CacheInfo'; import { contextConstant } from '@kit.AbilityKit';class ClearCache {// 清理缓存cleanAppCache(context: Context) {// el1加密分区context.getApplicationContext().area = contextConstant.AreaMode.EL1;context.area = contextConstant.AreaMode.EL1;const el1AppCacheDir = context.getApplicationContext().cacheDirconst el1HapCacheDir = context.cacheDir// el2加密分区context.getApplicationContext().area = contextConstant.AreaMode.EL2;context.area = contextConstant.AreaMode.EL2;const el2AppCacheDir = context.getApplicationContext().cacheDirconst el2HapCacheDir = context.cacheDirconst task = [this.clearCacheTask(el1AppCacheDir),this.clearCacheTask(el1HapCacheDir),this.clearCacheTask(el2AppCacheDir),this.clearCacheTask(el2HapCacheDir)]Promise.all(task).then(() => {this.getCache()})}clearCacheTask(dir: string): Promise<boolean> {return new Promise((resolve) => {fileIo.access(dir).then((exist: boolean) => {if (exist) {fileIo.rmdir(dir)}resolve(true)})})}// 获取缓存数据大小async getCache(): Promise<CacheInfo> {return storageStatistics.getCurrentBundleStats().then((res) => {let cache = (res.cacheSize / (1024 * 1024)).toFixed(2) + 'MB';let cacheInfo = new CacheInfo();cacheInfo.cache_size = cache;return cacheInfo;});} }export const clearCache = new ClearCache()
以上是工具类,下面的是 Bean 对象
@Observed export class CacheInfo {cache_path: string = "";cache_size: string = ""; }