2

我有一个 WebView 控件,我想每次显示当前站点,但我认为 WebView 只显示站点的缓存版本。我尝试了这里找到的所有东西,但似乎没有任何效果。我还尝试从 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);
    }

清除缓存功能:

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

3 回答 3

9

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

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

通过 - https://stackoverflow.com/a/10701961/2250339

于 2013-04-16T15:42:01.167 回答
0

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

于 2013-04-18T08:02:46.970 回答
0

要从您的 APP 中清除 cookie:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookie();
于 2016-08-22T05:48:59.230 回答