Example usage for android.webkit CookieManager getInstance

List of usage examples for android.webkit CookieManager getInstance

Introduction

In this page you can find the example usage for android.webkit CookieManager getInstance.

Prototype

public static CookieManager getInstance() 

Source Link

Document

Gets the singleton CookieManager instance.

Usage

From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from   w  w w. ja v a  2s.co  m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.WHITE);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setText(getPostName());
            close.setTextSize(20.0f);
            close.setTextColor(android.graphics.Color.GRAY);
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(backResId);
            closeIcon.setBounds(0, 0, 40, 40);
            close.setPadding(0, 0, 0, 0);
            close.setBackgroundDrawable(null);
            close.setCompoundDrawables(closeIcon, null, null, null);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                //close.setBackgroundDrawable(closeIcon);
            } else {
                //close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            //toolbar.addView(actionButtonContainer);
            //toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.phonegap.bossbolo.plugin.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//w  ww  .jav a  2s  .  co m
 * @param header
 */
public String showWebPage(final String url, HashMap<String, Boolean> features, final String header) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    showZoomControls = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean zoom = features.get(ZOOM);
        if (zoom != null) {
            showZoomControls = zoom.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
        if (hardwareBack != null) {
            hadwareBackButton = hardwareBack.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            int backgroundColor = Color.parseColor("#46bff7");
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout  header
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(50)));
            toolbar.setPadding(this.dpToPixels(8), this.dpToPixels(10), this.dpToPixels(8),
                    this.dpToPixels(10));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);
            toolbar.setBackgroundColor(backgroundColor);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setWidth(this.dpToPixels(34));
            back.setHeight(this.dpToPixels(31));
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("back", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                    //                        goBack();
                }
            });

            // Edit Text Box
            titletext = new TextView(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, this.dpToPixels(65));
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, this.dpToPixels(10));
            titletext.setLayoutParams(textLayoutParams);
            titletext.setId(3);
            titletext.setSingleLine(true);
            titletext.setText(header);
            titletext.setTextColor(Color.WHITE);
            titletext.setGravity(Gravity.CENTER);
            titletext.setTextSize(TypedValue.COMPLEX_UNIT_PX, this.dpToPixels(20));
            titletext.setSingleLine();
            titletext.setEllipsize(TruncateAt.END);

            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams editLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            editLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            editLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setVisibility(View.GONE);

            // Forward button
            /*Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            {
            forward.setBackgroundDrawable(fwdIcon);
            }
            else
            {
            forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goForward();
            }
            });
                    
            // Edit Text Box
            edittext = new TextView(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                  navigate(edittext.getText().toString());
                  return true;
                }
                return false;
            }
            });
                    
                    
            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            {
            close.setBackgroundDrawable(closeIcon);
            }
            else
            {
            close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                closeDialog();
            }
            });*/

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(getShowZoomControls());
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            //                actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(titletext);
            //                toolbar.addView(edittext);
            //                toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from www  .  j  a  va2s  .co m*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    showZoomControls = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean zoom = features.get(ZOOM);
        if (zoom != null) {
            showZoomControls = zoom.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
        if (hardwareBack != null) {
            hadwareBackButton = hardwareBack.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            final Context ctx = cordova.getActivity();
            dialog = new InAppBrowserDialog(ctx, android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(ctx);
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(ctx);
            //Please, no more black!
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); // JAMIE REVIEW
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.CENTER_VERTICAL);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(ctx);
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            final ButtonAwesome back = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            back.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
            back.setText(ExternalResourceHelper.getStrings(ctx, "fa_chevron_left"));
            back.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    back.setBackgroundDrawable(backIcon);
            //                }
            //                else
            //                {
            //                    back.setBackground(backIcon);
            //                }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            final ButtonAwesome forward = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
            forward.setText(ExternalResourceHelper.getStrings(ctx, "fa_chevron_right"));
            forward.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    forward.setBackgroundDrawable(fwdIcon);
            //                }
            //                else
            //                {
            //                    forward.setBackground(fwdIcon);
            //                }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // external button
            ButtonAwesome external = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams externalLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            externalLayoutParams.addRule(RelativeLayout.RIGHT_OF, 3);
            external.setLayoutParams(externalLayoutParams);
            external.setContentDescription("Back Button");
            external.setId(7);
            external.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            external.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
            external.setText(ExternalResourceHelper.getStrings(ctx, "fa_external_link"));
            external.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            external.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    openExternal(edittext.getText().toString());
                    closeDialog();
                }
            });

            // Edit Text Box
            edittext = new EditText(ctx);
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0) {
                        if (inAppWebView.canGoBack()) {
                            back.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
                        } else {
                            back.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
                        }
                        if (inAppWebView.canGoForward()) {
                            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
                        } else {
                            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
                        }
                    }
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            ButtonAwesome close = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            close.setContentDescription("Close Button");
            close.setId(5);
            close.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            close.setText(ExternalResourceHelper.getStrings(ctx, "fa_times"));
            close.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            close.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    close.setBackgroundDrawable(closeIcon);
            //                }
            //                else
            //                {
            //                    close.setBackground(closeIcon);
            //                }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(ctx);
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(showZoomControls);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = ctx.getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE)
                        .getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);
            actionButtonContainer.addView(external);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            if (getShowLocationBar()) {
                toolbar.addView(edittext);
            }
            toolbar.setBackgroundColor(ExternalResourceHelper.getColor(ctx, "green"));
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            //if (getShowLocationBar()) {
            // Add our toolbar to our main view/layout
            main.addView(toolbar);
            //}

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:org.apache.cordova.core.FileTransfer.java

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 *
 * @param source        URL of the server to receive the file
 * @param target            Full path of the file on the file system
 *///from   w w w.ja  va2 s . c om
private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "download " + source + " to " + target);

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    final boolean trustEveryone = args.optBoolean(2);
    final String objectId = args.getString(3);
    final JSONObject headers = args.optJSONObject(4);

    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
    // Accept a path or a URI for the source.
    Uri tmpTarget = Uri.parse(target);
    final Uri targetUri = resourceApi
            .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
    if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    // TODO: refactor to also allow resources & content:
    if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) {
        Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection connection = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            File file = null;
            PluginResult result = null;
            TrackingInputStream inputStream = null;

            OutputStream outputStream = null;
            try {
                OpenForReadResult readResult = null;
                outputStream = resourceApi.openOutputStream(targetUri);

                file = resourceApi.mapUriToFile(targetUri);
                context.targetFile = file;

                Log.d(LOG_TAG, "Download file:" + sourceUri);

                FileProgressResult progress = new FileProgressResult();

                if (isLocalTransfer) {
                    readResult = resourceApi.openForRead(sourceUri);
                    if (readResult.length != -1) {
                        progress.setLengthComputable(true);
                        progress.setTotal(readResult.length);
                    }
                    inputStream = new SimpleTrackingInputStream(readResult.inputStream);
                } else {
                    // connect to server
                    // Open a HTTP connection to the URL based on protocol
                    connection = resourceApi.createHttpConnection(sourceUri);
                    if (useHttps && trustEveryone) {
                        // Setup the HTTPS connection class to trust everyone
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        oldSocketFactory = trustAllHosts(https);
                        // Save the current hostnameVerifier
                        oldHostnameVerifier = https.getHostnameVerifier();
                        // Setup the connection not to verify hostnames
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                    }

                    connection.setRequestMethod("GET");

                    // TODO: Make OkHttp use this CookieManager by default.
                    String cookie = CookieManager.getInstance().getCookie(sourceUri.toString());
                    if (cookie != null) {
                        connection.setRequestProperty("cookie", cookie);
                    }

                    // This must be explicitly set for gzip progress tracking to work.
                    connection.setRequestProperty("Accept-Encoding", "gzip");

                    // Handle the other headers
                    if (headers != null) {
                        addHeadersToRequest(connection, headers);
                    }

                    connection.connect();

                    if (connection.getContentEncoding() == null
                            || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                        // Only trust content-length header if we understand
                        // the encoding -- identity or gzip
                        progress.setLengthComputable(true);
                        progress.setTotal(connection.getContentLength());
                    }
                    inputStream = getInputStream(connection);
                }

                try {
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inputStream;
                    }

                    // write bytes to file
                    byte[] buffer = new byte[MAX_BUFFER_SIZE];
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, bytesRead);
                        // Send a progress event.
                        progress.setLoaded(inputStream.getTotalRawBytesRead());
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }
                } finally {
                    context.currentInputStream = null;
                    safeClose(inputStream);
                    safeClose(outputStream);
                }

                Log.d(LOG_TAG, "Saved file: " + target);

                // create FileEntry object
                JSONObject fileEntry = FileUtils.getEntry(file);

                result = new PluginResult(PluginResult.Status.OK, fileEntry);
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
            } catch (Throwable e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } finally {
                safeClose(outputStream);
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (connection != null) {
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }

                if (result == null) {
                    result = new PluginResult(PluginResult.Status.ERROR,
                            createFileTransferError(CONNECTION_ERR, source, target, connection));
                }
                // Remove incomplete download.
                if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
                    file.delete();
                }
                context.sendPluginResult(result);
            }
        }
    });
}

From source file:com.tct.mail.ui.ConversationViewFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //TS: chao-zhang 2015-12-10 EMAIL BUGFIX_1121860 MOD_S    544
    //NOTE: when infalte conversationView which is implements from WebView,webview.jar is not exist
    //or not found,NameNotFoundException exception thrown,and InflateException thrown in Email,BAD!!!
    View rootView;//from   ww  w .ja  va  2  s.  c o  m
    try {
        rootView = inflater.inflate(R.layout.conversation_view, container, false);
    } catch (InflateException e) {
        LogUtils.e(LOG_TAG, e, "InflateException happen during inflate conversationView");
        //TS: xing.zhao 2016-4-1 EMAIL BUGFIX_1892015 MOD_S
        if (getActivity() == null) {
            return null;
        } else {
            rootView = new View(getActivity().getApplicationContext());
            return rootView;
        }
        //TS: xing.zhao 2016-4-1 EMAIL BUGFIX_1892015 MOD_E
    }
    //TS: chao-zhang 2015-12-10 EMAIL BUGFIX_1121860 MOD_E
    //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_S
    //Here we romve the imagebutton and then add it ,to make it show on the top level.
    //Because we can't add the fab button at last on the layout xml.
    mFabButton = (ConversationReplyFabView) rootView.findViewById(R.id.conversation_view_fab);
    FrameLayout framelayout = (FrameLayout) rootView.findViewById(R.id.conversation_view_framelayout);
    framelayout.removeView(mFabButton);
    framelayout.addView(mFabButton);
    //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_E
    mConversationContainer = (ConversationContainer) rootView.findViewById(R.id.conversation_container);
    mConversationContainer.setAccountController(this);

    mTopmostOverlay = (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay);
    mTopmostOverlay.setOnKeyListener(this);
    inflateSnapHeader(mTopmostOverlay, inflater);
    mConversationContainer.setupSnapHeader();

    setupNewMessageBar();

    mProgressController = new ConversationViewProgressController(this, getHandler());
    mProgressController.instantiateProgressIndicators(rootView);

    mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.conversation_webview);
    //TS: junwei-xu 2015-3-25 EMAIL BUGFIX_919767 ADD_S
    if (mWebView != null) {
        mWebView.setActivity(getActivity());
    }
    //TS: junwei-xu 2015-3-25 EMAIL BUGFIX_919767 ADD_E
    //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_S
    mWebView.setFabButton(mFabButton);
    //TS: tao.gan 2015-09-10 EMAIL FEATURE-559891 ADD_E

    mWebView.addJavascriptInterface(mJsBridge, "mail");
    // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
    // Below JB, try to speed up initial render by having the webview do supplemental draws to
    // custom a software canvas.
    // TODO(mindyp):
    //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
    // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
    // animation that immediately runs on page load. The app uses this as a signal that the
    // content is loaded and ready to draw, since WebView delays firing this event until the
    // layers are composited and everything is ready to draw.
    // This signal does not seem to be reliable, so just use the old method for now.
    final boolean isJBOrLater = Utils.isRunningJellybeanOrLater();
    final boolean isUserVisible = isUserVisible();
    mWebView.setUseSoftwareLayer(!isJBOrLater);
    mEnableContentReadySignal = isJBOrLater && isUserVisible;
    mWebView.onUserVisibilityChanged(isUserVisible);
    mWebView.setWebViewClient(mWebViewClient);
    final WebChromeClient wcc = new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
                //TS: wenggangjin 2015-01-29 EMAIL BUGFIX_-917007 MOD_S
                //                    LogUtils.wtf(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
                LogUtils.w(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(),
                        consoleMessage.lineNumber(), ConversationViewFragment.this);
                //TS: wenggangjin 2015-01-29 EMAIL BUGFIX_-917007 MOD_E
            } else {
                LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(),
                        consoleMessage.lineNumber(), ConversationViewFragment.this);
            }
            return true;
        }
    };
    mWebView.setWebChromeClient(wcc);

    final WebSettings settings = mWebView.getSettings();

    final ScrollIndicatorsView scrollIndicators = (ScrollIndicatorsView) rootView
            .findViewById(R.id.scroll_indicators);
    scrollIndicators.setSourceView(mWebView);

    settings.setJavaScriptEnabled(true);

    ConversationViewUtils.setTextZoom(getResources(), settings);
    //Enable third-party cookies. b/16014255
    if (Utils.isRunningLOrLater()) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true /* accept */);
    }

    mViewsCreated = true;
    mWebViewLoadedData = false;

    return rootView;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url/*from ww w .  jav  a  2  s .  com*/
 * @param features
 * @return
 */
public String showWebPage(final String url, final Options features) {
    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new ThemeableBrowserDialog(cordova.getActivity(), android.R.style.Theme_Black_NoTitleBar,
                    features.hardwareback);
            if (!features.disableAnimation) {
                dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            }
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setThemeableBrowser(getThemeableBrowser());

            // Main container layout
            ViewGroup main = null;

            if (features.fullscreen) {
                main = new FrameLayout(cordova.getActivity());
            } else {
                main = new LinearLayout(cordova.getActivity());
                ((LinearLayout) main).setOrientation(LinearLayout.VERTICAL);
            }

            // Toolbar layout
            Toolbar toolbarDef = features.toolbar;
            FrameLayout toolbar = new FrameLayout(cordova.getActivity());
            toolbar.setBackgroundColor(hexStringToColor(
                    toolbarDef != null && toolbarDef.color != null ? toolbarDef.color : "#ffffffff"));
            toolbar.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,
                    dpToPixels(toolbarDef != null ? toolbarDef.height : TOOLBAR_DEF_HEIGHT)));

            if (toolbarDef != null && (toolbarDef.image != null || toolbarDef.wwwImage != null)) {
                try {
                    Drawable background = getImage(toolbarDef.image, toolbarDef.wwwImage,
                            toolbarDef.wwwImageDensity);
                    setBackground(toolbar, background);
                } catch (Resources.NotFoundException e) {
                    emitError(ERR_LOADFAIL,
                            String.format("Image for toolbar, %s, failed to load", toolbarDef.image));
                } catch (IOException ioe) {
                    emitError(ERR_LOADFAIL,
                            String.format("Image for toolbar, %s, failed to load", toolbarDef.wwwImage));
                }
            }

            // Left Button Container layout
            LinearLayout leftButtonContainer = new LinearLayout(cordova.getActivity());
            FrameLayout.LayoutParams leftButtonContainerParams = new FrameLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            leftButtonContainerParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
            leftButtonContainer.setLayoutParams(leftButtonContainerParams);
            leftButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);

            // Right Button Container layout
            LinearLayout rightButtonContainer = new LinearLayout(cordova.getActivity());
            FrameLayout.LayoutParams rightButtonContainerParams = new FrameLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            rightButtonContainerParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
            rightButtonContainer.setLayoutParams(rightButtonContainerParams);
            rightButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Back button
            final Button back = createButton(features.backButton, "back button", new View.OnClickListener() {
                public void onClick(View v) {
                    emitButtonEvent(features.backButton, inAppWebView.getUrl());

                    if (features.backButtonCanClose && !canGoBack()) {
                        closeDialog();
                    } else {
                        goBack();
                    }
                }
            });

            if (back != null) {
                back.setEnabled(features.backButtonCanClose);
            }

            // Forward button
            final Button forward = createButton(features.forwardButton, "forward button",
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            emitButtonEvent(features.forwardButton, inAppWebView.getUrl());

                            goForward();
                        }
                    });

            if (forward != null) {
                forward.setEnabled(false);
            }

            // Close/Done button
            Button close = createButton(features.closeButton, "close button", new View.OnClickListener() {
                public void onClick(View v) {
                    emitButtonEvent(features.closeButton, inAppWebView.getUrl());
                    closeDialog();
                }
            });

            // Menu button
            Spinner menu = features.menu != null ? new MenuSpinner(cordova.getActivity()) : null;
            if (menu != null) {
                menu.setLayoutParams(
                        new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                menu.setContentDescription("menu button");
                setButtonImages(menu, features.menu, DISABLED_ALPHA);

                // We are not allowed to use onClickListener for Spinner, so we will use
                // onTouchListener as a fallback.
                menu.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            emitButtonEvent(features.menu, inAppWebView.getUrl());
                        }
                        return false;
                    }
                });

                if (features.menu.items != null) {
                    HideSelectedAdapter<EventLabel> adapter = new HideSelectedAdapter<EventLabel>(
                            cordova.getActivity(), android.R.layout.simple_spinner_item, features.menu.items);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    menu.setAdapter(adapter);
                    menu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                            if (inAppWebView != null && i < features.menu.items.length) {
                                emitButtonEvent(features.menu.items[i], inAppWebView.getUrl(), i);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> adapterView) {
                        }
                    });
                }
            }

            // Title
            final TextView title = features.title != null ? new TextView(cordova.getActivity()) : null;
            final TextView subtitle = features.title != null ? new TextView(cordova.getActivity()) : null;
            if (title != null) {
                FrameLayout.LayoutParams titleParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.FILL_PARENT);
                titleParams.gravity = Gravity.CENTER;
                title.setLayoutParams(titleParams);
                title.setSingleLine();
                title.setEllipsize(TextUtils.TruncateAt.END);
                title.setGravity(Gravity.CENTER | Gravity.TOP);
                title.setTextColor(
                        hexStringToColor(features.title.color != null ? features.title.color : "#000000ff"));
                title.setTypeface(title.getTypeface(), Typeface.BOLD);
                title.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);

                FrameLayout.LayoutParams subtitleParams = new FrameLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT);
                titleParams.gravity = Gravity.CENTER;
                subtitle.setLayoutParams(subtitleParams);
                subtitle.setSingleLine();
                subtitle.setEllipsize(TextUtils.TruncateAt.END);
                subtitle.setGravity(Gravity.CENTER | Gravity.BOTTOM);
                subtitle.setTextColor(hexStringToColor(
                        features.title.subColor != null ? features.title.subColor : "#000000ff"));
                subtitle.setTextSize(TypedValue.COMPLEX_UNIT_PT, 6);
                subtitle.setVisibility(View.GONE);

                if (features.title.staticText != null) {
                    title.setGravity(Gravity.CENTER);
                    title.setText(features.title.staticText);
                } else {
                    subtitle.setVisibility(View.VISIBLE);
                }
            }

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            final ViewGroup.LayoutParams inAppWebViewParams = features.fullscreen
                    ? new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
                    : new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);
            if (!features.fullscreen) {
                ((LinearLayout.LayoutParams) inAppWebViewParams).weight = 1;
            }
            inAppWebView.setLayoutParams(inAppWebViewParams);
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new ThemeableBrowserClient(thatWebView, new PageLoadListener() {

                @Override
                public void onPageStarted(String url) {
                    if (inAppWebView != null && title != null && features.title != null
                            && features.title.staticText == null && features.title.showPageTitle
                            && features.title.loadingText != null) {
                        title.setText(features.title.loadingText);
                        subtitle.setText(url);
                    }
                }

                @Override
                public void onPageFinished(String url, boolean canGoBack, boolean canGoForward) {
                    if (inAppWebView != null && title != null && features.title != null
                            && features.title.staticText == null && features.title.showPageTitle) {
                        title.setText(inAppWebView.getTitle());
                        subtitle.setText(inAppWebView.getUrl());
                    }

                    if (back != null) {
                        back.setEnabled(canGoBack || features.backButtonCanClose);
                    }

                    if (forward != null) {
                        forward.setEnabled(canGoForward);
                    }
                }
            });
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(features.zoom);
            settings.setDisplayZoomControls(false);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null
                    || appSettings.getBoolean("ThemeableBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("themeableBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (features.clearcache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (features.clearsessioncache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add buttons to either leftButtonsContainer or
            // rightButtonsContainer according to user's alignment
            // configuration.
            int leftContainerWidth = 0;
            int rightContainerWidth = 0;

            if (features.customButtons != null) {
                for (int i = 0; i < features.customButtons.length; i++) {
                    final BrowserButton buttonProps = features.customButtons[i];
                    final int index = i;
                    Button button = createButton(buttonProps, String.format("custom button at %d", i),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (inAppWebView != null) {
                                        emitButtonEvent(buttonProps, inAppWebView.getUrl(), index);
                                    }
                                }
                            });

                    if (ALIGN_RIGHT.equals(buttonProps.align)) {
                        rightButtonContainer.addView(button);
                        rightContainerWidth += button.getLayoutParams().width;
                    } else {
                        leftButtonContainer.addView(button, 0);
                        leftContainerWidth += button.getLayoutParams().width;
                    }
                }
            }

            // Back and forward buttons must be added with special ordering logic such
            // that back button is always on the left of forward button if both buttons
            // are on the same side.
            if (forward != null && features.forwardButton != null
                    && !ALIGN_RIGHT.equals(features.forwardButton.align)) {
                leftButtonContainer.addView(forward, 0);
                leftContainerWidth += forward.getLayoutParams().width;
            }

            if (back != null && features.backButton != null && ALIGN_RIGHT.equals(features.backButton.align)) {
                rightButtonContainer.addView(back);
                rightContainerWidth += back.getLayoutParams().width;
            }

            if (back != null && features.backButton != null && !ALIGN_RIGHT.equals(features.backButton.align)) {
                leftButtonContainer.addView(back, 0);
                leftContainerWidth += back.getLayoutParams().width;
            }

            if (forward != null && features.forwardButton != null
                    && ALIGN_RIGHT.equals(features.forwardButton.align)) {
                rightButtonContainer.addView(forward);
                rightContainerWidth += forward.getLayoutParams().width;
            }

            if (menu != null) {
                if (features.menu != null && ALIGN_RIGHT.equals(features.menu.align)) {
                    rightButtonContainer.addView(menu);
                    rightContainerWidth += menu.getLayoutParams().width;
                } else {
                    leftButtonContainer.addView(menu, 0);
                    leftContainerWidth += menu.getLayoutParams().width;
                }
            }

            if (close != null) {
                if (features.closeButton != null && ALIGN_RIGHT.equals(features.closeButton.align)) {
                    rightButtonContainer.addView(close);
                    rightContainerWidth += close.getLayoutParams().width;
                } else {
                    leftButtonContainer.addView(close, 0);
                    leftContainerWidth += close.getLayoutParams().width;
                }
            }

            // Add the views to our toolbar
            toolbar.addView(leftButtonContainer);
            // Don't show address bar.
            // toolbar.addView(edittext);
            toolbar.addView(rightButtonContainer);

            if (title != null) {
                int titleMargin = Math.max(leftContainerWidth, rightContainerWidth);

                FrameLayout.LayoutParams titleParams = (FrameLayout.LayoutParams) title.getLayoutParams();
                titleParams.setMargins(titleMargin, 8, titleMargin, 0);
                toolbar.addView(title);
            }

            if (subtitle != null) {
                int subtitleMargin = Math.max(leftContainerWidth, rightContainerWidth);

                FrameLayout.LayoutParams subtitleParams = (FrameLayout.LayoutParams) subtitle.getLayoutParams();
                subtitleParams.setMargins(subtitleMargin, 0, subtitleMargin, 8);
                toolbar.addView(subtitle);
            }

            if (features.fullscreen) {
                // If full screen mode, we have to add inAppWebView before adding toolbar.
                main.addView(inAppWebView);
            }

            // Don't add the toolbar if its been disabled
            if (features.location) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            if (!features.fullscreen) {
                // If not full screen, we add inAppWebView after adding toolbar.
                main.addView(inAppWebView);
            }

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (features.hidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.citrus.sdk.CitrusClient.java

/**
 * Signin with mobile no and password./*from ww w  . j  av  a2s.c  o  m*/
 *
 * @param mobileNo
 * @param password
 * @param callback
 */
public synchronized void signInWithMobileNo(final String mobileNo, final String password,
        final Callback<CitrusResponse> callback) {

    //grant Type username token saved
    retrofitClient.getSignInToken(signinId, signinSecret, mobileNo, OAuth2GrantType.username.toString(),
            new retrofit.Callback<AccessToken>() {

                @Override
                public void success(AccessToken accessToken, Response response) {
                    if (accessToken.getHeaderAccessToken() != null) {
                        OauthToken token = new OauthToken(mContext, SIGNIN_TOKEN);
                        token.createToken(accessToken.getJSON());///grant Type username token saved

                        retrofitClient.getSignInWithPasswordResponse(signinId, signinSecret, mobileNo, password,
                                OAuth2GrantType.password.toString(), new retrofit.Callback<AccessToken>() {
                                    @Override
                                    public void success(AccessToken accessToken, Response response) {
                                        Logger.d("SIGN IN RESPONSE " + accessToken.getJSON().toString());
                                        if (accessToken.getHeaderAccessToken() != null) {
                                            final OauthToken token = new OauthToken(mContext, PREPAID_TOKEN);
                                            token.createToken(accessToken.getJSON());///grant Type password token saved

                                            // Fetch the associated emailId and save the emailId.
                                            // This is async since we are just updating the details and not dependent upon the response.
                                            getMemberInfo(null, mobileNo, new Callback<MemberInfo>() {
                                                @Override
                                                public void success(MemberInfo memberInfo) {
                                                    if (memberInfo != null
                                                            && memberInfo.getProfileByMobile() != null) {

                                                        token.saveUserDetails(
                                                                memberInfo.getProfileByMobile().getEmailId(),
                                                                mobileNo);//save email ID of the signed in user
                                                    }
                                                }

                                                @Override
                                                public void error(CitrusError error) {
                                                    // NOOP
                                                    // Do nothing
                                                }
                                            });

                                            // Activate user's prepaid account, if not already.
                                            activatePrepaidUser(new Callback<Amount>() {
                                                @Override
                                                public void success(Amount amount) {
                                                    RetroFitClient.setInterCeptor();
                                                    EventBus.getDefault().register(CitrusClient.this);
                                                    retrofitClient.getCookie(mobileNo, password, "true",
                                                            new retrofit.Callback<String>() {
                                                                @Override
                                                                public void success(String s,
                                                                        Response response) {
                                                                    // NOOP
                                                                    // This method will never be called.
                                                                }

                                                                @Override
                                                                public void failure(RetrofitError error) {
                                                                    if (prepaidCookie != null) {
                                                                        cookieManager = CookieManager
                                                                                .getInstance();
                                                                        PersistentConfig config = new PersistentConfig(
                                                                                mContext);
                                                                        if (config.getCookieString() != null) {
                                                                            cookieManager.getInstance()
                                                                                    .removeSessionCookie();
                                                                        }
                                                                        CookieSyncManager
                                                                                .createInstance(mContext);
                                                                        config.setCookie(prepaidCookie);
                                                                    } else {
                                                                        Logger.d("PREPAID LOGIN UNSUCCESSFUL");
                                                                    }
                                                                    EventBus.getDefault()
                                                                            .unregister(CitrusClient.this);

                                                                    // Since we have a got the cookie, we are giving the callback.
                                                                    sendResponse(callback, new CitrusResponse(
                                                                            ResponseMessages.SUCCESS_MESSAGE_SIGNIN,
                                                                            Status.SUCCESSFUL));
                                                                }
                                                            });
                                                }

                                                @Override
                                                public void error(CitrusError error) {
                                                    sendError(callback, error);
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void failure(RetrofitError error) {
                                        Logger.d("SIGN IN RESPONSE ERROR **" + error.getMessage());
                                        sendError(callback, error);
                                    }
                                });

                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    sendError(callback, error);
                }
            });
}

From source file:de.baumann.browser.Browser_right.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from w ww  .  j  a  v  a2 s .  c o m*/
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_right.this, editText, 3, "", getString(R.string.app_search_hint));
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser_right.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search_chooseWebsite) {
        helper_editText.editText_searchWeb(editText, Browser_right.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser_right.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();

        if (Uri.parse(mWebView.getUrl()).getHost().length() == 0) {
            domain = getString(R.string.app_domain);
        } else {
            domain = Uri.parse(mWebView.getUrl()).getHost();
        }

        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser_right.this);
        View dialogView = View.inflate(Browser_right.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser_right.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser_right").apply();
                helper_main.switchToActivity(Browser_right.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.menu_save_screenshot) {
        screenshot();
    }

    if (id == R.id.menu_save_bookmark) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.editText_saveBookmark(editText, Browser_right.this, mWebView);
    }

    if (id == R.id.menu_save_readLater) {
        DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
        db.open();
        if (db.isExist(mWebView.getUrl())) {
            Snackbar.make(editText, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
        } else {
            db.insert(helper_webView.getTitle(mWebView), mWebView.getUrl(), "", "", helper_main.createDate());
            Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG).show();
        }
    }

    if (id == R.id.menu_save_pass) {
        helper_editText.editText_savePass(Browser_right.this, mWebView, mWebView.getTitle(), mWebView.getUrl());
    }

    if (id == R.id.menu_createShortcut) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setClassName(Browser_right.this, "de.baumann.browser.Browser_left");
        i.setData(Uri.parse(mWebView.getUrl()));

        Intent shortcut = new Intent();
        shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
        shortcut.putExtra("android.intent.extra.shortcut.NAME", "THE NAME OF SHORTCUT TO BE SHOWN");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                .fromContext(Browser_right.this.getApplicationContext(), R.mipmap.ic_launcher));
        shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        Browser_right.this.sendBroadcast(shortcut);
        Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.menu_share_screenshot) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("image/png");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        Uri bmpUri = Uri.fromFile(shareFile);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_screenshot))));
    }

    if (id == R.id.menu_share_link) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
    }

    if (id == R.id.menu_share_link_copy) {
        String url = mWebView.getUrl();
        ClipboardManager clipboard = (ClipboardManager) Browser_right.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
        Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.action_downloads) {
        helper_main.switchToActivity(Browser_right.this, Popup_files.class, "", false);
    }

    if (id == R.id.action_search_go) {

        String text = editText.getText().toString();
        helper_webView.openURL(Browser_right.this, mWebView, editText);
        helper_editText.hideKeyboard(Browser_right.this, editText, 0, text,
                getString(R.string.app_search_hint));
        helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    if (id == R.id.action_search_onSite) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_right.this, editText, 1, "", getString(R.string.app_search_hint));
        helper_editText.editText_FocusChange_searchSite(editText, Browser_right.this);
        helper_editText.editText_searchSite(editText, Browser_right.this, mWebView, urlBar);
    }

    if (id == R.id.action_search_onSite_go) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser_right.this, mWebView, urlBar);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser_right.this, editText, 1,
                    getString(R.string.app_search) + " " + text, getString(R.string.app_search_hint_site));
        }
    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        urlBar.setVisibility(View.VISIBLE);
        urlBar.setText(mWebView.getTitle());
        editText.setVisibility(View.GONE);
        helper_editText.editText_FocusChange(editText, Browser_right.this);
        helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
        helper_editText.hideKeyboard(Browser_right.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser_right.this, mWebView);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    return super.onOptionsItemSelected(item);
}

From source file:de.baumann.browser.Browser_left.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*  w ww  .j av  a 2 s. c  o  m*/
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_left.this, editText, 3, "", getString(R.string.app_search_hint));
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser_left.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search_chooseWebsite) {
        helper_editText.editText_searchWeb(editText, Browser_left.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser_left.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();

        if (Uri.parse(mWebView.getUrl()).getHost().length() == 0) {
            domain = getString(R.string.app_domain);
        } else {
            domain = Uri.parse(mWebView.getUrl()).getHost();
        }

        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser_left.this);
        View dialogView = View.inflate(Browser_left.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser_left.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser_left").apply();
                helper_main.switchToActivity(Browser_left.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.menu_save_screenshot) {
        screenshot();
    }

    if (id == R.id.menu_save_bookmark) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.editText_saveBookmark(editText, Browser_left.this, mWebView);
    }

    if (id == R.id.menu_save_readLater) {
        DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_left.this);
        db.open();
        if (db.isExist(mWebView.getUrl())) {
            Snackbar.make(editText, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
        } else {
            db.insert(helper_webView.getTitle(mWebView), mWebView.getUrl(), "", "", helper_main.createDate());
            Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG).show();
        }
    }

    if (id == R.id.menu_save_pass) {
        helper_editText.editText_savePass(Browser_left.this, mWebView, mWebView.getTitle(), mWebView.getUrl());
    }

    if (id == R.id.menu_createShortcut) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setClassName(Browser_left.this, "de.baumann.browser.Browser_left");
        i.setData(Uri.parse(mWebView.getUrl()));

        Intent shortcut = new Intent();
        shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
        shortcut.putExtra("android.intent.extra.shortcut.NAME", "THE NAME OF SHORTCUT TO BE SHOWN");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                .fromContext(Browser_left.this.getApplicationContext(), R.mipmap.ic_launcher));
        shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        Browser_left.this.sendBroadcast(shortcut);
        Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.menu_share_screenshot) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("image/png");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        Uri bmpUri = Uri.fromFile(shareFile);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_screenshot))));
    }

    if (id == R.id.menu_share_link) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
    }

    if (id == R.id.menu_share_link_copy) {
        String url = mWebView.getUrl();
        ClipboardManager clipboard = (ClipboardManager) Browser_left.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
        Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.action_downloads) {
        helper_main.switchToActivity(Browser_left.this, Popup_files.class, "", false);
    }

    if (id == R.id.action_search_go) {

        String text = editText.getText().toString();
        helper_webView.openURL(Browser_left.this, mWebView, editText);
        helper_editText.hideKeyboard(Browser_left.this, editText, 0, text, getString(R.string.app_search_hint));
        helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    if (id == R.id.action_search_onSite) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_left.this, editText, 1, "", getString(R.string.app_search_hint));
        helper_editText.editText_FocusChange_searchSite(editText, Browser_left.this);
        helper_editText.editText_searchSite(editText, Browser_left.this, mWebView, urlBar);
    }

    if (id == R.id.action_search_onSite_go) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser_left.this, mWebView, urlBar);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser_left.this, editText, 1,
                    getString(R.string.app_search) + " " + text, getString(R.string.app_search_hint_site));
        }
    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        urlBar.setVisibility(View.VISIBLE);
        urlBar.setText(mWebView.getTitle());
        editText.setVisibility(View.GONE);
        helper_editText.editText_FocusChange(editText, Browser_left.this);
        helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
        helper_editText.hideKeyboard(Browser_left.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser_left.this, mWebView);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    return super.onOptionsItemSelected(item);
}

From source file:de.baumann.browser.Browser.java

@SuppressLint("SetJavaScriptEnabled")
@Override/* w  ww  .  j a va2  s .c  o m*/
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {

        mWebView.stopLoading();
        String text = editText.getText().toString();
        String searchEngine = sharedPref.getString("searchEngine", "https://startpage.com/do/search?query=");
        String wikiLang = sharedPref.getString("wikiLang", "en");

        if (text.length() > 3) {
            subStr = text.substring(3);
        }

        if (text.equals(mWebView.getTitle()) || text.isEmpty()) {
            helper_editText.showKeyboard(Browser.this, editText, 3, "", getString(R.string.app_search_hint));

        } else {
            helper_editText.hideKeyboard(Browser.this, editText, 0, text, getString(R.string.app_search_hint));
            helper_editText.editText_EditorAction(editText, Browser.this, mWebView);

            if (text.startsWith("www")) {
                mWebView.loadUrl("http://" + text);
            } else if (text.contains("http")) {
                mWebView.loadUrl(text);
            } else if (text.contains(".w ")) {
                mWebView.loadUrl("https://" + wikiLang + ".wikipedia.org/wiki/Spezial:Suche?search=" + subStr);
            } else if (text.startsWith(".f ")) {
                mWebView.loadUrl("https://www.flickr.com/search/?advanced=1&license=2%2C3%2C4%2C5%2C6%2C9&text="
                        + subStr);
            } else if (text.startsWith(".m ")) {
                mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + subStr);
            } else if (text.startsWith(".g ")) {
                mWebView.loadUrl("https://github.com/search?utf8=&q=" + subStr);
            } else if (text.startsWith(".s ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl(
                            "https://startpage.com/do/search?query=" + subStr + "&lui=deutsch&l=deutsch");
                } else {
                    mWebView.loadUrl("https://startpage.com/do/search?query=" + subStr);
                }
            } else if (text.startsWith(".G ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://www.google.de/search?&q=" + subStr);
                } else {
                    mWebView.loadUrl("https://www.google.com/search?&q=" + subStr);
                }
            } else if (text.startsWith(".y ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://www.youtube.com/results?hl=de&gl=DE&search_query=" + subStr);
                } else {
                    mWebView.loadUrl("https://www.youtube.com/results?search_query=" + subStr);
                }
            } else if (text.startsWith(".d ")) {
                if (Locale.getDefault().getLanguage().contentEquals("de")) {
                    mWebView.loadUrl("https://duckduckgo.com/?q=" + subStr
                            + "&kl=de-de&kad=de_DE&k1=-1&kaj=m&kam=osm&kp=-1&kak=-1&kd=1&t=h_&ia=web");
                } else {
                    mWebView.loadUrl("https://duckduckgo.com/?q=" + subStr);
                }
            } else {
                if (searchEngine.contains("https://duckduckgo.com/?q=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl("https://duckduckgo.com/?q=" + text
                                + "&kl=de-de&kad=de_DE&k1=-1&kaj=m&kam=osm&kp=-1&kak=-1&kd=1&t=h_&ia=web");
                    } else {
                        mWebView.loadUrl("https://duckduckgo.com/?q=" + text);
                    }
                } else if (searchEngine.contains("https://metager.de/meta/meta.ger3?focus=web&eingabe=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + text);
                    } else {
                        mWebView.loadUrl("https://metager.de/meta/meta.ger3?focus=web&eingabe=" + text
                                + "&focus=web&encoding=utf8&lang=eng");
                    }
                } else if (searchEngine.contains("https://startpage.com/do/search?query=")) {
                    if (Locale.getDefault().getLanguage().contentEquals("de")) {
                        mWebView.loadUrl(
                                "https://startpage.com/do/search?query=" + text + "&lui=deutsch&l=deutsch");
                    } else {
                        mWebView.loadUrl("https://startpage.com/do/search?query=" + text);
                    }
                } else {
                    mWebView.loadUrl(searchEngine + text);
                }
            }
        }
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search3) {
        helper_editText.editText_searchWeb(editText, Browser.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();
        String link = mWebView.getUrl();
        int domainInt = link.indexOf("//") + 2;
        final String domain = link.substring(domainInt, link.indexOf('/', domainInt));
        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser.this);
        View dialogView = View.inflate(Browser.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser").apply();
                helper_main.switchToActivity(Browser.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.action_save) {
        final CharSequence[] options = { getString(R.string.menu_save_screenshot),
                getString(R.string.menu_save_bookmark), getString(R.string.menu_save_readLater),
                getString(R.string.menu_save_pass), getString(R.string.menu_createShortcut) };
        new AlertDialog.Builder(Browser.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_save_bookmark))) {
                            helper_editText.editText_saveBookmark(editText, Browser.this, mWebView);
                        }
                        if (options[item].equals(getString(R.string.menu_save_pass))) {
                            helper_editText.editText_savePass(Browser.this, mWebView, mWebView.getTitle(),
                                    mWebView.getUrl());
                        }
                        if (options[item].equals(getString(R.string.menu_save_readLater))) {
                            try {
                                final Database_ReadLater db = new Database_ReadLater(Browser.this);
                                db.addBookmark(mWebView.getTitle(), mWebView.getUrl());
                                db.close();
                                Snackbar.make(mWebView, R.string.readLater_added, Snackbar.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_save_screenshot))) {
                            screenshot();
                        }
                        if (options[item].equals(getString(R.string.menu_createShortcut))) {
                            Intent i = new Intent();
                            i.setAction(Intent.ACTION_VIEW);
                            i.setClassName(Browser.this, "de.baumann.browser.Browser");
                            i.setData(Uri.parse(mWebView.getUrl()));

                            Intent shortcut = new Intent();
                            shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
                            shortcut.putExtra("android.intent.extra.shortcut.NAME",
                                    "THE NAME OF SHORTCUT TO BE SHOWN");
                            shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
                            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                                    .fromContext(Browser.this.getApplicationContext(), R.mipmap.ic_launcher));
                            shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                            Browser.this.sendBroadcast(shortcut);
                            Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }).show();
    }

    if (id == R.id.action_share) {
        final CharSequence[] options = { getString(R.string.menu_share_screenshot),
                getString(R.string.menu_share_link), getString(R.string.menu_share_link_copy) };
        new AlertDialog.Builder(Browser.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_share_link))) {
                            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                            sharingIntent.setType("text/plain");
                            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
                            sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                            startActivity(
                                    Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
                        }
                        if (options[item].equals(getString(R.string.menu_share_screenshot))) {
                            screenshot();

                            if (shareFile.exists()) {
                                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                sharingIntent.setType("image/png");
                                sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
                                sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                                Uri bmpUri = Uri.fromFile(shareFile);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                                startActivity(Intent.createChooser(sharingIntent,
                                        (getString(R.string.app_share_screenshot))));
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_share_link_copy))) {
                            String url = mWebView.getUrl();
                            ClipboardManager clipboard = (ClipboardManager) Browser.this
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                            Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }).show();
    }

    if (id == R.id.action_downloads) {
        String startDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getPath();
        helper_main.openFilePicker(Browser.this, mWebView, startDir);
    }

    if (id == R.id.action_searchSite) {
        mWebView.stopLoading();
        helper_editText.editText_FocusChange_searchSite(editText, Browser.this);
        helper_editText.editText_searchSite(editText, Browser.this, mWebView);
    }

    if (id == R.id.action_search2) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser.this, mWebView);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser.this, editText, 1, getString(R.string.app_search) + " " + text,
                    getString(R.string.app_search_hint_site));
        }

    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        helper_editText.editText_FocusChange(editText, Browser.this);
        helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
        helper_editText.hideKeyboard(Browser.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser.this, mWebView);
    }

    return super.onOptionsItemSelected(item);
}