Android – How to enable cookies in android webview

androidwebview

How do I enable cookies in a webview?

I tried to use

CookieManager.getInstance().setAcceptCookie(true);

just before calling WebView.loadUrl() and it doesn't work as I get an HTML page error from a website saying cookies need to be enabled.

How does cookieManager know which webview to enable cookies?

Say if I had an activity with two webviews in the screen and I only wanted one of those webviews to enable cookies, how is that possible using a CookieManager?

I feel like I am missing something. I could not find a method like webView.setCookieManager or Cookiemanager.setWebView(webview).

Best Answer

You should consider that

CookieManager.getInstance().setAcceptCookie(true);

doesn't work from lollipop(API21) and above. You should check and use appropriate function for that case:

if (android.os.Build.VERSION.SDK_INT >= 21) {   
     CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
} else {
     CookieManager.getInstance().setAcceptCookie(true);
}