我有一个使用 webview 并利用缓存的应用程序。但即使应用程序没有运行,我也需要每 X 分钟清除一次缓存。我该怎么做呢?
我已经像这样启用了缓存:
myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
myWebView.getSettings().setAppCacheEnabled(true);
我使用此语句通过按钮删除缓存:
myWebView.clearCache(true);
最佳答案
上面由 Gaunt Face 发布的编辑后的代码 fragment 包含一个错误,如果一个目录由于其中一个文件无法删除而无法删除,则代码将在无限循环中不断重试。我将其重写为真正的递归,并添加了 numDays 参数,以便您可以控制要修剪的文件的年龄:
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
关于java - 如何每 X 分钟清除一次应用程序缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969436/