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

- moduleContext = await application.createModuleContext(this.context, 'entry')
- // 缓存路径/data/storage/el2/base/cache
- paths.push(moduleContext.cacheDir)
- // 缓存路径/data/storage/el2/base/haps/entry/cache
- paths.push(this.context.cacheDir)
- // 缓存路径/data/storage/el1/base/cache
- moduleContext.area = contextConstant.AreaMode.EL1
- paths.push(moduleContext.cacheDir)
- // 缓存路径/data/storage/el1/base/haps/entry/cache
- context.area = contextConstant.AreaMode.EL1
- paths.push(this.context.cacheDir)
- // 获取完需要清理的路径之后,moduleContext.area和context.area需要切换回应用原本的加密分区,否则可能会影响其他业务功能。
- clearAllCache() {
- this.paths.forEach((cacheDir) => {
- hilog.info(0x0000, 'CacheClean', cacheDir)
- this.deleteFile(cacheDir)
- })
- }
-
- deleteFile(cacheDir: string) {
- fs.listFile(cacheDir)
- .then((filenames) => {
- filenames.forEach((name) => {
- let dirPath = cacheDir + '/' + name
- hilog.info(0x0000, 'CacheClean', dirPath)
- // 判断是否为文件夹
- 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)
- })
- }
- })
- })
- }
- ├──entry/src/main/ets
- │ ├──entryability
- │ │ └──EntryAbility.ets
- │ ├──model
- │ │ └──SettingModel.ets // 设置列表
- │ └──pages
- │ └──CacheClean.ets // 主页面
- └──entry/src/main/resources // 应用资源目录