Requirement Description
When using context.cacheDir to retrieve and clear the application cache, the cache is not completely removed. After calling storageStatistics.getCurrentBundleStats to check the cache size, the result still shows that the cache size is not zero.
Background Knowledge
Application cache refers to temporary data generated during app operation, such as images, videos, and documents.
This data helps improve response speed and provides offline capabilities, but excessive cache can occupy significant storage space.
The @ohos.file.storageStatistics module provides functions to query storage space usage, including:
- Internal and external storage queries
- App-specific data classification and usage statistics
In HarmonyOS, app cache files are distributed across four directories:
/data/storage/el1/base/cache
/data/storage/el1/base/haps/entry/cache
/data/storage/el2/base/cache
/data/storage/el2/base/haps/entry/cache
Using only context.cacheDir clears one directory (/data/storage/el2/base/haps/entry/cache), leaving residual cache in the other locations.
Implementation Steps
- Obtain paths for all four cache directories (EL1 and EL2 levels).
- Store the cache directory paths into an array for iteration.
- Traverse the array and delete all files and subdirectories in each path to ensure complete cache removal.
Code Snippet / Configuration
Step 1: Get all cache directory paths
private paths: Array<string> = [];
private moduleContext: common.Context | undefined = undefined;
private context: Context | undefined = undefined;
async aboutToAppear(): Promise<void> {
this.context = this.getUIContext().getHostContext()!;
this.moduleContext = await application.createModuleContext(this.context, 'entry');
console.info(`moduleContext + el2: ${this.moduleContext.cacheDir}`); // /data/storage/el2/base/cache
console.info(`UIAbilityContext + el2: ${this.context.cacheDir}`); // /data/storage/el2/base/haps/entry/cache
this.paths.push(this.moduleContext.cacheDir);
this.paths.push(this.context.cacheDir);
this.moduleContext.area = contextConstant.AreaMode.EL1;
console.info(`moduleContext + el1: ${this.moduleContext.cacheDir}`); // /data/storage/el1/base/cache
this.context.area = contextConstant.AreaMode.EL1;
console.info(`UIAbilityContext + el1: ${this.context.cacheDir}`); // /data/storage/el1/base/haps/entry/cache
this.paths.push(this.moduleContext.cacheDir);
this.paths.push(this.context.cacheDir);
}
Step 2: Delete files in all cache directories
Button('Clear Cache').onClick(() => {
for (let i = 0; i < this.paths.length; i++) {
let path = this.paths[i];
fileIo.listFile(path).then((filenames) => {
for (let i = 0; i < filenames.length; i++) {
let dirPath = path + '/' + filenames[i];
console.info(dirPath);
let isDirectory: boolean = false;
try {
isDirectory = fileIo.statSync(dirPath).isDirectory();
} catch (err) {
console.error(`Failed to check directory: ${err.message}`);
}
if (isDirectory) {
fileIo.rmdirSync(dirPath);
} else {
fileIo.unlink(dirPath).then(() => {
console.info('File removed successfully');
}).catch((err: Error) => {
console.error(`Failed to remove file: ${err.message}`);
});
}
}
});
}
});
Test Results
After executing the above code, all cache directories are cleared successfully.
Calling storageStatistics.getCurrentBundleStats returns a cacheSize value of 0, confirming full cache deletion.
Limitations or Considerations
- Supported from API Version 19 Release and later.
- Requires HarmonyOS 5.1.1 Release SDK or newer.
- Must be compiled and executed using DevEco Studio 5.1.1 Release or later.
- Apps should decide the level of cache cleanup based on their requirements.
Related Documents or Links
https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-file-storage-statistics
https://developer.huawei.com/consumer/en/doc/harmonyos-faqs/faqs-local-file-manager-12

Top comments (0)