Android Webview - 完全清除缓存

Mat*_*unt 103 android caching webview

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

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

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

我也遵循了这里的建议:如何为WebView清空缓存?

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

    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"));
Run Code Online (Sandbox Code Playgroud)

所以我实现了第一个建议(尽管改变了代码是递归的)

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这仍未改变页面显示的内容.在我的桌面浏览器上,我得到了不同的HTML代码到WebView中生成的网页,所以我知道WebView必须在某处缓存.

在IRC频道上,我指出了一个修复,以从URL连接中删除缓存,但无法看到如何将其应用于WebView.

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

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

Aks*_*hat 191

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

WebView obj;
obj.clearCache(true);
Run Code Online (Sandbox Code Playgroud)

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

我一直试图找出清除缓存的方法,但我们可以从上面提到的方法做的就是删除本地文件,但它从不清理RAM.

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

  • 这里最好的答案. (11认同)
  • 我没有运气。想知道有什么改变吗?我可以使用 google.com 加载 WebView,即使在 clearCache(true); 之后,WebView 仍然认为我已登录; (2认同)
  • @lostintranslation为此,您可能要删除cookie。尽管我敢肯定您现在已经发现了。 (2认同)

mar*_*jan 43

由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));
}
Run Code Online (Sandbox Code Playgroud)

希望对其他人有用:)


Sco*_*ott 40

我找到了你要找的修复:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这会在蜂窝中引发一个令人讨厌的异常:06-14 22:33:34.349:ERROR/SQLiteDatabase(20382):无法打开数据库.关闭它.06-14 22:33:34.349:ERROR/SQLiteDatabase(20382):android.database.sqlite.SQLiteDiskIOException:disk I/O error 06-14 22:33:34.349:ERROR/SQLiteDatabase(20382):at android.database. sqlite.SQLiteDatabase.native_setLocale(本机方法) (2认同)

ama*_*Bit 33

要在您的APP上签名时清除所有webview缓存:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookie();
Run Code Online (Sandbox Code Playgroud)

对于棒棒糖及以上:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookies(ValueCallback);
Run Code Online (Sandbox Code Playgroud)

  • 如果您无法在活动中访问Webview,则效果很好。另请注意,此API已被弃用,因此请在L +设备上使用“ removeAllCookies(ValueCallback)” API。 (2认同)

Sri*_*san 12

要从 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();
Run Code Online (Sandbox Code Playgroud)


Ket*_*ani 6

唯一适合我的解决方案

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();
} 
Run Code Online (Sandbox Code Playgroud)