我在应用程序中使用以下方法:
@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
CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager=CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
我从片段中以以下方式调用此方法:
mWebView.clearCache(true);
mWebView.clearHistory();
U.clearCookies(getActivity());
mWebView.loadUrl(authorizeURL);
在通过以下方式呼叫clearCookies之前和之后,都可以转储该域的Cookie:
String yahooCookies = CookieManager.getInstance().getCookie("https://yahoo.com");
Log.d(C.TAG, "Cookies for yahoo.com:" + yahooCookies);
致电clearCookies之后,yahooCookies将为null。
此实现满足了我的需求,我已经在多个仿真器上以及在史前的Android 2.3.3三星Galaxy Gio和Android 5.1.1 Nexus 5上进行了测试。