简体   繁体   English

Android Webview - 完全清除缓存

[英]Android Webview - Completely Clear the Cache

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.在我的桌面浏览器上,我得到的 html 代码与 WebView 中生成的 web 页面不同,所以我知道 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, ie 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.主要问题是对网页中的链接进行了更改,因此网页的前端完全没有变化。

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,因此要求再次加载网页。

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

And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.别担心,这些数据库只是与您的应用程序相关联,因此您不会清除整个手机的缓存。

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

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);

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();

The only solution that works for me唯一对我有用的解决方案

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

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");
    }
}

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

WebView(applicationContext).clearCache(true)
webView.clearCache(true)
appFormWebView.clearFormData()
appFormWebView.clearHistory()
appFormWebView.clearSslPreferences()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
WebStorage.getInstance().deleteAllData()

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

getSettings().setSaveFormData(false);

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

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

It can clear google account in my webview它可以在我的 webview 中清除谷歌帐户

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

Did the trick成功了

to completely clear the cache in kotlin you can use:要完全清除 kotlin 中的缓存,您可以使用:

context.cacheDir.deleteRecursively()

Just in case someone needs the kotlin code (:以防万一有人需要 kotlin 代码(:

Previous code has been deprecated.以前的代码已被弃用。 So, you can try this one in Kotlin base android projects:因此,您可以在 Kotlin 基础 android 项目中尝试这个:

CookieManager.getInstance().removeAllCookies {  
   // Do your work here.
}

use case: list of item are displaying in recycler view, whenever any item click it hides recycler view and shows web view with item url.用例:项目列表显示在回收站视图中,每当单击任何项​​目时,它都会隐藏回收站视图并显示带有项目 url 的 Web 视图。

problem: i have similar problem in which once i open a url_one in webview , then try to open another url_two in webview, it shows url_one in background till url_two is loaded.问题:我有类似的问题,一旦我在 webview 中打开一个url_one ,然后尝试在 webview 中打开另一个url_two ,它url_one后台显示url_one直到url_two被加载。

solution: so to solve what i did is load blank string "" as url just before hiding url_one and loading url_two .解决方案:所以要解决我所做的就是在隐藏url_one和加载url_two之前加载空白字符串""作为url

output: whenever i load any new url in webview it does not show any other web page in background.输出:每当我在 webview 中加载任何新 url 时,它都不会在后台显示任何其他网页。

code代码

public void showWebView(String url){
        webView.loadUrl(url);
        recyclerView.setVisibility(View.GONE);
        webView.setVisibility(View.VISIBLE);
    }

public void onListItemClick(String url){
   showWebView(url);
}

public void hideWebView(){
        // loading blank url so it overrides last open url
        webView.loadUrl("");
        webView.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);
   }


 @Override
public void onBackPressed() {
    if(webView.getVisibility() == View.VISIBLE){
        hideWebView();
    }else{
        super.onBackPressed();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM