简体   繁体   中英

Read & Store cookies created in WebView

I have a Android Application which is basically uses WebView for all interaction..

How can i access (read) Cookies which are created in WebView (if someone logs in) and than store them somewhere, maybe in SharedPreferences, so that later i can use them.

For example.. on quitting the application .. i can say "Thank Mr.XYZ,do u really want to quit"

Here is my code...

package com.example.hellowebview;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class HelloWebView extends Activity {
WebView webview;

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

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

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    webview = (WebView) findViewById(R.id.webview);
    webview.setWebViewClient(new HelloWebViewClient(

    ));

    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("http://www.mysite.com/mobile");
}

public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Thank <<Name Cookie value from Webview >>>,do u really want to quit?")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

}

To work with WebView cookies, you can use CookieManager which has some getter and setter methods for you.

http://developer.android.com/reference/android/webkit/CookieManager.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM