0%

[转] How to clear cookies and cache of webview on Android when not in webview?

原文地址:http://stackoverflow.com/a/31950789

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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();
}
}

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

1
2
3
4
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:

1
2
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.

坚持原创及高品质技术分享,您的支持将鼓励我继续创作!