How to save a cookie in an Android webview forever?

You have to tell the CookieSyncManager to sync after it has loaded the page in question. In your sample code, the onCreate method executes completely before the WebView tries to load the page, so the sync process (which happens asynchronously) will probably complete before the page is loaded.

Instead, tell the CookieSyncManager to sync onPageFinished in the WebViewClient. That should get you what you want.

The CookieSyncManager Documentation is a good read for how to do this properly.

Here is how you could set up your WebViewClient implementation to do this for you:

webview.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        //Users will be notified in case there's an error (i.e. no internet connection)
        Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
    }

    public void onPageFinished(WebView view, String url) {
        CookieSyncManager.getInstance().sync();
    }
);

You would not need to tell the CookieSyncManager to sync elsewhere with this in place. I haven’t tested this, so let me know if it works.

Leave a Comment