java - 如何每 X 分钟清除一次应用程序缓存?

标签 java android caching android-webview

我有一个使用 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/

相关文章:

javascript - Android 上的 PhoneGap 选择框行为不当

android - 文本对齐 :center not working in CDATA in string. xml

ruby-on-rails - 在 Rails 中缓存 JSON 结果

ios - 将 NSMutableDictionary 设置为 nil 是否会释放对其所有内容的引用?

java - 使用 shell 脚本运行 jar 文件时限制 kill 命令

java - 在循环中累积字符串并打印出所有字符串

java - 如何访问 WAR 的根目录?

java - 为什么全局变量不随同一个全局变量中的全局函数更新?安卓/Java

android - 如何在 Android 中管理多个 Activity 交互?

Spring @Cacheable 默认 TTL