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;
}
// 定義一個異步函數(shù)來遞歸獲取目錄內(nèi)所有文件的總大小
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()) {
//如果是文件夾,那么就繼續(xù)遍歷
totalSize += await this.getDirectorySizeAsync(filePath);
} else {
//如果是文件魏铅,就直接獲取文件大小
totalSize += await this.getFileSizeAsync(filePath);
}
}
} catch (error) {
console.error(`Error listing files in ${directoryPath}:`, error);
}
return totalSize;
}
// 定義一個異步函數(shù)來處理文件大小的累加
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()
}
}
使用的時候直接調(diào)用:
獲取app緩存大胁獭:
let cacheSize = await TBXCacheManager.getInstance().getAppCacheSize()
cacheModel.subtitle = String(cacheSize) + 'M'
清理app緩存:
TBXCacheManager.getInstance().removeAppAllCache( async () => {
//處理后續(xù)邏輯,比如更改UI上緩存大小顯示
})