How to programmatically accept cookies on Android Studio’s WebView? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to programmatically accept cookies on Android Studio’s WebView? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have made a web app and would like to programmatically allow cookies, so the ‘allow cookies’ message from the website do not pop up in my app.

So far, I have this:

public class MainActivity extends AppCompatActivity {


WebView webview;
ImageView Logo, FondBlanc;
ProgressBar progressBar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this,R.style.DialogStyle);
    alertDialogBuilder.setTitle("Unable to connect");
    alertDialogBuilder.setMessage("Please check your Internet connection");
    alertDialogBuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String url = webview.getUrl();
            webview.loadUrl(url);
            Error = "";
        }
    });
    alertDialogBuilder.setCancelable(false);
    final AlertDialog alertDialog = alertDialogBuilder.create();

    Logo = findViewById(R.id.logo);
    FondBlanc = findViewById(R.id.fondBlanc);
    progressBar = findViewById(R.id.progressbar);
    progressBar.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);

    Error = "";

    webview = findViewById(R.id.webView);
    webview.setWebViewClient(new WebViewClient(){

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            String host = Uri.parse(url).getHost();
            String domain = "mywebsite.com";

            if (host.equals(domain)) {
                // This is my website, so do not override; let my WebView load the page
                return false;
            } else {
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }

        @Override public void onReceivedError(WebView view, WebResourceRequest request,
                                              WebResourceError error) {
            super.onReceivedError(view, request, error);

            webview.stopLoading();

            Error = error.toString();

            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setAllCaps(false);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(18);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#FFFFFF"));
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundResource(R.drawable.dialog_style);

        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                                              HttpAuthHandler handler, String host, String realm) {

            handler.proceed("username", "password");

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (Error.equals("")) {
                progressBar.setVisibility(View.GONE);
                Logo.setImageResource(0);
                FondBlanc.setImageResource(0);
            }
        }
    });


    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true);
        CookieManager.getInstance().acceptThirdPartyCookies(webview);
    } else {
        CookieManager.getInstance().setAcceptCookie(true);
    }
    CookieManager.setAcceptFileSchemeCookies(true);
    webview.loadUrl("mywebsite.com");

}
}

But I still get the ‘allow cookies’ message: cookies

I would like to get rid of this message without manually accepting it, how can I please do that ? I’ve tried using different methods I found with CookiesManager but none of them worked.

Thank you in advance for your help.

Answer

I figured it out after several hours:

CookieSyncManager.createInstance(webview.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeSessionCookie();

    cookieManager.setCookie(domain,"cookies-state=accepted");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.flush();
    } else {
        CookieSyncManager.getInstance().sync();
    }
We are here to answer your question about How to programmatically accept cookies on Android Studio’s WebView? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji