乐闻世界logo
搜索文章和话题

How to save a cookie in an Android webview forever?

1个答案

1

In Android WebView, cookies are saved by default, but they are not persistently stored because WebView uses the system's CookieManager to manage cookies. The system's CookieManager stores cookies in memory by default and clears them upon session termination or device reboot.

To achieve persistent cookie storage, follow these steps:

  1. Enable WebView's Cookie Management: First, ensure that WebView's cookie management is enabled. Use the CookieManager class to control WebView's cookie management. Here is an example code snippet to enable cookies:

    java
    CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true);
  2. Persist Cookies: To permanently save cookies, synchronize them to persistent storage. Use the flush method of CookieManager to synchronize cookies from memory to disk, ensuring they can be loaded and used even after the application closes or the device restarts. Here is an example code snippet for persisting cookies:

    java
    cookieManager.flush();

    Note that starting from Android 5.0 (API level 21), the flush method is automatically invoked, so manual invocation is typically unnecessary. However, if you need to immediately synchronize cookies from memory to disk, you can still manually call this method.

  3. Configure WebView's Cookie Policy: The latest Android SDK provides the setAcceptThirdPartyCookies method to set whether WebView accepts third-party cookies. If the pages loaded in your WebView require third-party cookies, enable this option:

    java
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.setAcceptThirdPartyCookies(webView, true); }
  4. Manage Cookie Compatibility: Due to differences in how various Android versions manage cookies, you may need to write compatibility code to ensure persistent cookie storage works across different Android versions.

  5. Synchronize Cookies on Exit: To ensure cookies are synchronized to disk upon application exit, call the flush method of CookieManager in the onPause or onStop methods of Activity.

    java
    @Override protected void onPause() { super.onPause(); CookieManager.getInstance().flush(); }
  6. Example: Suppose an application has a login feature implemented via WebView. After the user logs in by entering a username and password in the WebView, the server issues cookies to maintain the session. To ensure the user remains logged in when reopening the app, these cookies need to be saved in the WebView. Follow the steps above to configure CookieManager, ensuring cookies are saved and the flush method is called at appropriate times to synchronize cookies to disk.

By following these steps, you can achieve persistent cookie storage in Android applications' WebView, ensuring consistent user experience and persistent sessions.

2024年6月29日 12:07 回复

你的答案