To enable cookies in Android WebView, you need to use the CookieManager class to manage cookies for your WebView. Here are the steps to enable cookie support:
- Obtain an instance of
CookieManager. - Enable or disable cookies using the
setAcceptCookiemethod.
Here is a simple example code:
javaimport android.webkit.CookieManager; import android.webkit.WebView; // When initializing the WebView WebView webView = new WebView(context); // Obtain an instance of CookieManager CookieManager cookieManager = CookieManager.getInstance(); // Enable cookie storage for the WebView cookieManager.setAcceptCookie(true); // If you are using Android Lollipop (API 21) or higher, you can also enable third-party cookies in this way: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.setAcceptThirdPartyCookies(webView, true); } // Now you can load URLs that require cookies webView.loadUrl("http://www.example.com");
In this example, setAcceptCookie(true) enables cookies for the WebView. If you are developing an app targeting Android Lollipop (API 21) or higher, you can also use setAcceptThirdPartyCookies to decide whether to accept third-party cookies.
Note that in practice, you may also need to handle cookie persistence issues. By default, cookies are stored in RAM, and they may be lost after the app is closed. To persist cookies, you can use CookieSyncManager on Android 4.4 and earlier to synchronize cookies, or on Android 4.4 and later, use the flush method to ensure cookies in memory are synchronized to disk.
java// For Android 4.4 and earlier, use CookieSyncManager to synchronize cookies CookieSyncManager.createInstance(context); CookieSyncManager.getInstance().sync(); // On Android 4.4 and later, directly use CookieManager's flush method to synchronize cookies to disk if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.flush(); }
Note that as Android versions continue to evolve, these APIs and practices may change. Therefore, refer to the latest official documentation when using them.