How to maintain session in WebView after exiting the application in Android?

5.4k views Asked by At

I'm currently new to Android development but I'm trying to create a simple android app that opens up my website and allows you to log into it in WebView. However, I realized that when you exit the application and terminate its process and relaunch the application, it asks you to re-log back in, instead of staying logged in. I'm not sure how to go about to solve this issue. I've looked into the implementation of CookieManager, however, I'm not able to get that to work correctly. Could you help show me what I'm doing wrong?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView)findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.acceptCookie();
        String cookie = CookieManager.getInstance().getCookie("myWebsite");
        myWebView.loadUrl("myWebsite");
        myWebView.setWebViewClient(new WebViewClient());
    }
1

There are 1 answers

0
memt On

I ran into the same trouble.

Try to setup the WebviewSettings like so:

webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);

And flush the cookies from the in memory database to the persistent memory.

CookieManager.getInstance().flush()

After the flush, the cookies should exist even after a full app-relaunch.

Access the Cookies using:

CookieManager.getInstance().getCookie(yourUrlString)