簡體   English   中英

Android Webview - 完全清除緩存

[英]Android Webview - Completely Clear the Cache

我的一個活動中有一個 WebView,當它加載網頁時,該頁面從 Facebook 收集一些背景數據。

不過,我看到的是,每次打開和刷新應用程序時,應用程序中顯示的頁面都是相同的。

我嘗試將 WebView 設置為不使用緩存並清除 WebView 的緩存和歷史記錄。

我也遵循了這里的建議: How to empty cache for 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"));

所以我實施了第一個建議(雖然將代碼更改為遞歸)

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

但是,這仍然沒有改變頁面顯示的內容。 在我的桌面瀏覽器上,我得到的 html 代碼與 WebView 中生成的 web 頁面不同,所以我知道 WebView 必須緩存在某處。

在 IRC 頻道上,有人指出了一個從 URL 連接中刪除緩存的修復程序,但還看不到如何將其應用於 WebView。

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

如果我刪除我的應用程序並重新安裝它,我可以獲得最新的網頁,即非緩存版本。 主要問題是對網頁中的鏈接進行了更改,因此網頁的前端完全沒有變化。

我找到了一個更優雅和簡單的清除緩存的解決方案

WebView obj;
obj.clearCache(true);

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

我一直在試圖找出清除緩存的方法,但是我們從上述方法中所能做的就是刪除本地文件,但它從未清理過 RAM。

API clearCache 釋放 webview 使用的 RAM,因此要求再次加載網頁。

我找到了您正在尋找的修復程序:

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

出於某種原因,Android 對 url 進行了錯誤的緩存,它會意外返回而不是您需要的新數據。 當然,您可以只從數據庫中刪除條目,但在我的情況下,我只是嘗試訪問一個 URL,因此吹走整個數據庫更容易。

別擔心,這些數據庫只是與您的應用程序相關聯,因此您不會清除整個手機的緩存。

上面由 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));
}

希望對其他人有用:)

要在退出應用程序時清除所有 webview 緩存:

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

對於棒棒糖及以上:

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

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

唯一對我有用的解決方案

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

這應該清除您的應用程序緩存,這應該是您的 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);

要清除歷史記錄,只需執行以下操作:

this.appView.clearHistory();

來源: 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();

它可以在我的 webview 中清除谷歌帳戶

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

成功了

要完全清除 kotlin 中的緩存,您可以使用:

context.cacheDir.deleteRecursively()

以防萬一有人需要 kotlin 代碼(:

以前的代碼已被棄用。 因此,您可以在 Kotlin 基礎 android 項目中嘗試這個:

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

用例:項目列表顯示在回收站視圖中,每當單擊任何項​​目時,它都會隱藏回收站視圖並顯示帶有項目 url 的 Web 視圖。

問題:我有類似的問題,一旦我在 webview 中打開一個url_one ,然后嘗試在 webview 中打開另一個url_two ,它url_one后台顯示url_one直到url_two被加載。

解決方案:所以要解決我所做的就是在隱藏url_one和加載url_two之前加載空白字符串""作為url

輸出:每當我在 webview 中加載任何新 url 時,它都不會在后台顯示任何其他網頁。

代碼

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