66

Upon a user's sign out from my app I am clearing everything that may have been cached previously from the webview by calling this method:

 public void clearCookiesAndCache(Context context){
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.removeAllCookies(null);
    }
    else {
        cookieManager.removeAllCookie();
    }        
}

CookieSyncManager is marked as deprecated, however. CookieSyncManager.createInstance(context) is necessary to be called, however, if you have not loaded the webview previously. So how are we supposed to clear the cookies and cache without using the deprecated CookieSyncManager in cases where the webview may not have been previously loaded?

JohnRock
  • 6,475
  • 12
  • 50
  • 61

5 Answers5

144

I use the following approach in my app:

    @SuppressWarnings("deprecation")
    public static void clearCookies(Context context)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            Log.d(C.TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
            CookieManager.getInstance().removeAllCookies(null);
            CookieManager.getInstance().flush();
        } else
        {
            Log.d(C.TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
            CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
            cookieSyncMngr.startSync();
            CookieManager cookieManager=CookieManager.getInstance();
            cookieManager.removeAllCookie();
            cookieManager.removeSessionCookie();
            cookieSyncMngr.stopSync();
            cookieSyncMngr.sync();
        }
    }

Or in Kotlin

@SuppressWarnings("deprecation")
fun clearCookies(context: Context?) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        CookieManager.getInstance().removeAllCookies(null)
        CookieManager.getInstance().flush()
    } else if (context != null) {
        val cookieSyncManager = CookieSyncManager.createInstance(context)
        cookieSyncManager.startSync()
        val cookieManager: CookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        cookieManager.removeSessionCookie()
        cookieSyncManager.stopSync()
        cookieSyncManager.sync()
    }
}

I call this method in the following manner from my fragment:

mWebView.clearCache(true);
mWebView.clearHistory();
    
U.clearCookies(getActivity());
    
mWebView.loadUrl(authorizeURL);

It is possible to dump the cookies for a domain before and after the call to clearCookies by

String yahooCookies = CookieManager.getInstance().getCookie("https://yahoo.com");
Log.d(C.TAG, "Cookies for yahoo.com:" + yahooCookies);

After calling clearCookies yahooCookies will be null.

This implementation feeds my needs, I have tested it on several emulators and a prehistoric Samsung Galaxy Gio with Android 2.3.3 and Nexus 5 with Android 5.1.1.

jobbert
  • 2,655
  • 17
  • 38
AdamVe
  • 2,826
  • 2
  • 16
  • 12
  • 5
    you have +1 from me, 10x about this code, but please change the the first letter of ClearCookies to be lower case (clearCookies) this is Java – Stoycho Andreev Apr 22 '16 at 10:38
  • 1
    Your code snippet has worked like god for us. I have been struggling with webview cache issue. Clearing cache did not work but clearing cookies worked. Thanks alot!!!!!!!! I was facing issue in integration ccavenue payment gateway issue in webview. – krisDrOid Jun 16 '16 at 15:32
  • 1
    Thanks man!!!!! You saved my day.This solution working awesome.. Once thanks a lot – sandeepmaaram Jun 16 '16 at 16:17
  • 1
    I was getting crashes on devices running SDK 21. CookieSyncManger was deprecated on 21 -> https://developer.android.com/reference/android/webkit/CookieSyncManager.html. Should be "Build.VERSION_CODES.LOLLIPOP" – mikemike396 Dec 06 '16 at 17:37
  • 1
    Hi! What's the purpose of calling CookieManager.getInstance().flush(); ? according to documentation https://developer.android.com/reference/android/webkit/CookieManager.html#flush() it's not related to clearing cookies... – hhg Nov 10 '17 at 19:56
  • Since `removeAllCookies` is an async operation, should we call `flush` inside `removeAllCookies`' callback? – Alex Napitupulu Apr 05 '19 at 15:01
  • Good Solution ! Thanks – MannersW Dec 04 '19 at 03:44
  • Why exactly the check for LOLLIPOP_MR1 (API 22) instead of LOLLIPOP (API 21)? All those apis seems to have been added in API 21 so I wondered if there was a particular reason for checking for 22 instead? – Leon Lucardie Dec 23 '20 at 11:08
22

Working and tested ..

android.webkit.CookieManager cookieManager = CookieManager.getInstance();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
         // a callback which is executed when the cookies have been removed
         @Override
         public void onReceiveValue(Boolean aBoolean) {
               Log.d(TAG, "Cookie removed: " + aBoolean);
         }
       });
}
else cookieManager.removeAllCookie();
Gayan Weerakutti
  • 7,029
  • 50
  • 55
9

To clear all the stored info from Webview,

// 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();
Srinivasan
  • 3,863
  • 3
  • 22
  • 33
7

I'm using this...

@WorkerThread
public static void clearCache() {
    new WebView(getApplicationContext()).clearCache(true);
}

Be careful to call it on a UI Thread otherwise you get an exception.

karllindmark
  • 5,771
  • 1
  • 23
  • 40
Pollizzio
  • 914
  • 7
  • 11
  • About how to get application context, refer to http://stackoverflow.com/questions/987072/using-application-context-everywhere – Pollizzio Jun 22 '15 at 10:24
  • Awesome! For me, cookieManager.removeAllCookies() never worked. The boolean value received was always false. But doing this way worked like a charm!! – rolgalan Nov 08 '16 at 18:03
4

I just had the same problem. I needed to delete all cookies because I didn't want to keep old ones and didn't want to use the deprecated method.

Here the documentation:

http://developer.android.com/reference/android/webkit/CookieManager.html

And here the method:

public abstract void removeAllCookies (ValueCallback callback)

In your case:

cookieManager.removeAllCookies(null);

should do the job. If with "null" it doesn't work, then you have to use a callback*...

Eventually you may find an answer here: Android WebView Cookie Problem

Hope this helps. Cheers

Community
  • 1
  • 1
firepol
  • 1,611
  • 22
  • 37