Android Webview - 彻底清除缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2465432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:56:57  来源:igfitidea点击:

Android Webview - Completely Clear the Cache

androidcachingwebview

提问by Matt Gaunt

I have a WebView in one of my Activities, and when it loads a webpage, the page gathers some background data from Facebook.

我的一个活动中有一个 WebView,当它加载网页时,该页面会从 Facebook 收集一些背景数据。

What I'm seeing though, is the page displayed in the application is the same on each time the app is opened and refreshed.

但我看到的是,每次打开和刷新应用程序时,应用程序中显示的页面都是相同的。

I've tried setting the WebView not to use cache and clear the cache and history of the WebView.

我尝试将 WebView 设置为不使用缓存并清除 WebView 的缓存和历史记录。

I've also followed the suggestion here: How to empty cache for WebView?

我也遵循了这里的建议:How to empty cache for WebView?

But none of this works, does anyone have any ideas of I can overcome this problem because it is a vital part of my application.

但是这些都不起作用,有没有人有任何想法我可以克服这个问题,因为它是我的应用程序的重要组成部分。

    mWebView.setWebChromeClient(new WebChromeClient()
    {
           public void onProgressChanged(WebView view, int progress)
           {
               if(progress >= 100)
               {
                   mProgressBar.setVisibility(ProgressBar.INVISIBLE);
               }
               else
               {
                   mProgressBar.setVisibility(ProgressBar.VISIBLE);
               }
           }
    });
    mWebView.setWebViewClient(new SignInFBWebViewClient(mUIHandler));
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.clearHistory();
    mWebView.clearFormData();
    mWebView.clearCache(true);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    Time time = new Time();
    time.setToNow();

    mWebView.loadUrl(mSocialProxy.getSignInURL()+"?time="+time.format("%Y%m%d%H%M%S"));

So I implemented the first suggestion (Although changed the code to be recursive)

所以我实现了第一个建议(虽然将代码更改为递归)

private void clearApplicationCache() {
    File dir = getCacheDir();

    if (dir != null && dir.isDirectory()) {
        try {
            ArrayList<File> stack = new ArrayList<File>();

            // Initialise the list
            File[] children = dir.listFiles();
            for (File child : children) {
                stack.add(child);
            }

            while (stack.size() > 0) {
                Log.v(TAG, LOG_START + "Clearing the stack - " + stack.size());
                File f = stack.get(stack.size() - 1);
                if (f.isDirectory() == true) {
                    boolean empty = f.delete();

                    if (empty == false) {
                        File[] files = f.listFiles();
                        if (files.length != 0) {
                            for (File tmp : files) {
                                stack.add(tmp);
                            }
                        }
                    } else {
                        stack.remove(stack.size() - 1);
                    }
                } else {
                    f.delete();
                    stack.remove(stack.size() - 1);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, LOG_START + "Failed to clean the cache");
        }
    }
}

However this still hasn't changed what the page is displaying. On my desktop browser I am getting different html code to the web page produced in the WebView so I know the WebView must be caching somewhere.

然而,这仍然没有改变页面显示的内容。在我的桌面浏览器上,我得到了与 WebView 中生成的网页不同的 html 代码,所以我知道 WebView 必须缓存在某处。

On the IRC channel I was pointed to a fix to remove caching from a URL Connection but can't see how to apply it to a WebView yet.

在 IRC 频道上,我指出了从 URL 连接中删除缓存的修复程序,但还看不到如何将其应用于 WebView。

http://www.androidsnippets.org/snippets/45/

http://www.androidsnippets.org/snippets/45/

If I delete my application and re-install it, I can get the webpage back up to date, i.e. a non-cached version. The main problem is the changes are made to links in the webpage, so the front end of the webpage is completely unchanged.

如果我删除我的应用程序并重新安装它,我可以将网页恢复到最新状态,即非缓存版本。主要问题是对网页中的链接进行了更改,因此网页的前端完全没有变化。

采纳答案by markjan

The edited code snippet above posted by Gaunt Face contains an error in that if a directory fails to delete because one of its files cannot be deleted, the code will keep retrying in an infinite loop. I rewrote it to be truly recursive, and added a numDays parameter so you can control how old the files must be that are pruned:

上面由 Gaunt Face 发布的编辑过的代码片段包含一个错误,即如果一个目录由于其中一个文件无法删除而无法删除,则该代码将继续无限循环重试。我将其重写为真正的递归,并添加了一个 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));
}

Hopefully of use to other people :)

希望对其他人有用:)

回答by Akshat

I found an even elegant and simple solution to clearing cache

我找到了一个更优雅和简单的清除缓存的解决方案

WebView obj;
obj.clearCache(true);

http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29

http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29

I have been trying to figure out the way to clear the cache, but all we could do from the above mentioned methods was remove the local files, but it never clean the RAM.

我一直在试图找出清除缓存的方法,但是我们从上述方法中所能做的就是删除本地文件,但它从未清理过 RAM。

The API clearCache, frees up the RAM used by the webview and hence mandates that the webpage be loaded again.

API clearCache 释放 webview 使用的 RAM,因此要求再次加载网页。

回答by Scott

I found the fix you were looking for:

我找到了您正在寻找的修复程序:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");

For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.

出于某种原因,Android 对 url 进行了错误的缓存,它会意外返回而不是您需要的新数据。当然,您可以只从数据库中删除条目,但在我的情况下,我只是尝试访问一个 URL,因此吹走整个数据库更容易。

And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.

别担心,这些数据库只是与您的应用程序相关联,因此您不会清除整个手机的缓存。

回答by amalBit

To clear all the webview caches while you signOUT form your APP:

要在退出应用程序时清除所有 webview 缓存:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookie();

For Lollipop and above:

对于棒棒糖及以上:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookies(ValueCallback);

回答by jqpubliq

This should clear your applications cache which should be where your webview cache is

这应该清除您的应用程序缓存,这应该是您的 webview 缓存所在的位置

File dir = getActivity().getCacheDir();

if (dir != null && dir.isDirectory()) {
    try {
        File[] children = dir.listFiles();
        if (children.length > 0) {
            for (int i = 0; i < children.length; i++) {
                File[] temp = children[i].listFiles();
                for (int x = 0; x < temp.length; x++) {
                    temp[x].delete();
                }
            }
        }
    } catch (Exception e) {
        Log.e("Cache", "failed cache clean");
    }
}

回答by Ercan

Simply using below code in Kotlin works for me

只需在 Kotlin 中使用以下代码即可为我工作

WebView(applicationContext).clearCache(true)

回答by Srinivasan

To clear cookie and cache from Webview,

要从 Webview 清除 cookie 和缓存,

    // Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
    WebStorage.getInstance().deleteAllData();

    // Clear all the cookies
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();

    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    webView.clearSslPreferences();

回答by Ketan Ramani

The only solution that works for me

唯一对我有用的解决方案

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();
} 

回答by Raghu

Make sure you use below method for the form data not be displayed as autopop when clicked on input fields.

确保您使用以下方法,当单击输入字段时,表单数据不会显示为自动弹出。

getSettings().setSaveFormData(false);

回答by Alan CN

To clear the history, simply do:

要清除历史记录,只需执行以下操作:

this.appView.clearHistory();

Source: http://developer.android.com/reference/android/webkit/WebView.html

来源:http: //developer.android.com/reference/android/webkit/WebView.html