Android WebView - 清除缓存

时间:2013-04-16 15:36:24

标签: android webview browser-cache

我有一个WebView控件,我希望每次显示当前站点,但我认为WebView只显示该站点的缓存版本。我尝试了所有找到的here,但似乎没有任何效果。我还试图从context.getCacheDir()中删除所有文件,但没有成功。我该怎么办?

这是我在onCreate方法中的代码:

    clearCache(this, 0);

    setContentView(R.layout.webview);

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

    mWebView = (WebView)findViewById(R.id.webview);
    mWebView.setWebViewClient(new CenterWebViewClient(this));
    mWebView.setWebChromeClient(new CenterWebChromeClient(this));
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.getSettings().setAppCacheMaxSize(1);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

    String  url = "https://www.exacmple.com";

    if (url != null) {
        Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
        noCacheHeaders.put("Pragma", "no-cache");
        noCacheHeaders.put("Cache-Control", "no-cache");
        mWebView.loadUrl(url, noCacheHeaders);
    }

clearCache函数:

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("WebView", String.format("Failed to clean the cache, error %s", e.getMessage()));
        }
    }
    return deletedFiles;
}

    public static void clearCache(final Context context, final int numDays) {
         Log.i("WebView", String.format("Starting cache prune, deleting files older than %d days", numDays));
         int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
         Log.i("WebView", String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
    }

3 个答案:

答案 0 :(得分:8)

似乎您可以在显示webview时清除缓存

 @Override
public void onPageFinished(WebView view, String url) {
     super.onPageFinished(view, url);
     view.clearCache(true);
}

via - https://stackoverflow.com/a/10701961/2250339

答案 1 :(得分:0)

这是一个问题,不是缓存,只有服务器端的会话,我不得不删除cookie,现在它可以工作。

答案 2 :(得分:0)

从您的APP中清除Cookie:

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