【问题标题】:How do I clear app cache every X minutes?如何每 X 分钟清除一次应用缓存?
【发布时间】:2019-09-17 07:35:24
【问题描述】:

我有一个使用 webview 并利用缓存的应用程序。但是即使应用程序没有运行,我也需要每 X 分钟清除一次缓存。我该怎么做?

我已经启用了这样的缓存:

        myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        myWebView.getSettings().setAppCacheEnabled(true);

我使用这个语句通过一个按钮来删除缓存:

myWebView.clearCache(true);

【问题讨论】:

  • 请提供更多细节。你指的是哪个缓存?
  • 编辑并添加了一些代码@maslan

标签: java android caching android-webview


【解决方案1】:

上面 Gaunt Face 发布的编辑后的代码 sn-p 包含一个错误,即如果一个目录因为其中一个文件无法删除而无法删除,代码将在无限循环中不断重试。我将其重写为真正的递归,并添加了一个 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));
}

【讨论】:

  • 关闭应用时它不会工作,不是吗?
  • 问题不在于删除缓存本身。它安排它每 X 分钟完成一次。
  • 后台进程需要使用Workmanager,即使应用程序关闭或杀死也能正常工作
【解决方案2】:
 public static void deleteDirectoryTree(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory()) {
            for (File child : fileOrDirectory.listFiles()) {
                deleteDirectoryTree(child);
            }
        }

        fileOrDirectory.delete();
    }


deleteDirectoryTree(this.getCacheDir());

您可以在 Activity 中设置一个计时器,并在指定的超时时间后,调用 deleteDirectoryTree

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 2023-03-30
    • 2017-04-11
    • 2014-11-02
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多