How to store cookies in an Android WebView?

14,056

Take a look at the CookieSyncManager class, basically you can do this:

CookieSyncManager syncManager = CookieSyncManager.createInstance(webView.getContext());
CookieManager cookieManager = CookieManager.getInstance();

cookieManager.setCookie(); // Here your cookie
syncManager.sync();
Share:
14,056
Nick Chubb
Author by

Nick Chubb

GO DAWGS

Updated on June 04, 2022

Comments

  • Nick Chubb
    Nick Chubb almost 2 years

    Currently I'm trying to store cookies in my android app. My app is loading a web page using the android webview. The activity is below.

    But, I need help to store cookies in my app. The web page I'm loading is creating the cookies with php using the setcookie() function. It works fine in a regular browser, but I'm a beginner app developer and it doesn't work in my android WebView.

    I need your help to store the cookie with php (on the loaded web page).

    P.S. I want the cookie to last forever (if possible).

    package com.stuff;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Window;
    import android.webkit.WebChromeClient;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;
    
    public class Activity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    
            // Let's display the progress in the activity title bar, like the
            // browser app does.
            getWindow().requestFeature(Window.FEATURE_PROGRESS);
    
            WebView webview = new WebView(this);
            setContentView(webview);
    
    
            webview.getSettings().setJavaScriptEnabled(true);
    
            final Activity activity = this;
            webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                 // Activities and WebViews measure progress with different scales.
                 // The progress meter will automatically disappear when we reach 100%
                 activity.setProgress(progress * 1000);
            }
          });
    
    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();
    }
    });
         //This will load the webpage that we want to see
          webview.loadUrl("http://www.need-cookies.com/");
    
       }
    }