Example usage for android.webkit WebView setWebViewClient

List of usage examples for android.webkit WebView setWebViewClient

Introduction

In this page you can find the example usage for android.webkit WebView setWebViewClient.

Prototype

public void setWebViewClient(WebViewClient client) 

Source Link

Document

Sets the WebViewClient that will receive various notifications and requests.

Usage

From source file:com.farmerbb.notepad.activity.MainActivity.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.KITKAT)//  w  w w  . jav a 2s  . c o m
public void printNote(String contentToPrint) {
    SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);

    // Create a WebView object specifically for printing
    boolean generateHtml = !(pref.getBoolean("markdown", false)
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
    WebView webView = generateHtml ? new WebView(this) : new MarkdownView(this);

    // Apply theme
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;

    String fontFamily = null;

    if (theme.contains("sans")) {
        fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom_print)
            / getResources().getDisplayMetrics().density) + "px";
    String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right_print)
            / getResources().getDisplayMetrics().density) + "px";
    String fontSize = " " + Integer.toString(textSize) + "px";

    String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
            + fontFamily + "; " + "font-size:" + fontSize + "; " + "}";

    webView.getSettings().setJavaScriptEnabled(false);
    webView.getSettings().setLoadsImagesAutomatically(false);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(final WebView view, String url) {
            createWebPrintJob(view);
        }
    });

    // Load content into WebView
    if (generateHtml) {
        webView.loadDataWithBaseURL(null,
                "<link rel='stylesheet' type='text/css' href='data:text/css;base64,"
                        + Base64.encodeToString(css.getBytes(), Base64.DEFAULT) + "' /><html><body><p>"
                        + StringUtils.replace(contentToPrint, "\n", "<br>") + "</p></body></html>",
                "text/HTML", "UTF-8", null);
    } else
        ((MarkdownView) webView).loadMarkdown(contentToPrint,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));
}

From source file:com.azure.webapi.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * //from  w  w  w. j a  v  a2  s  .  c o  m
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
protected void showLoginUI(MobileServiceAuthenticationProvider provider, final String startUrl,
        final String endUrl, final Context context, LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setTitle("Connecting to a service");
    builder.setCancelable(true);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    // Set cancel button's action
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
            wv.destroy();
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.microsoft.windowsazure.mobileservices.authentication.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 *
 * @param startUrl The initial URL for the authentication process
 * @param endUrl   The final URL for the authentication process
 * @param context  The context used to create the authentication dialog
 * @param callback Callback to invoke when the authentication process finishes
 *///from   ww w  .j av  a2s .c  o m
private void showLoginUIInternal(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels - 100;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished

            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.example.manan.enhancedurdureader.EpubReader.BookView.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override//  w  w w  . j a v  a 2 s .  co m
public void onActivityCreated(Bundle saved) {
    super.onActivityCreated(saved);
    view = (WebView) getView().findViewById(R.id.Viewport);
    view.getSettings().setTextZoom(textSize);

    mScaleDetector = new ScaleGestureDetector(getActivity().getBaseContext(),
            new ScaleGestureDetector.OnScaleGestureListener() {
                @Override
                public void onScaleEnd(ScaleGestureDetector detector) {
                }

                @Override
                public boolean onScaleBegin(ScaleGestureDetector detector) {
                    return true;
                }

                @Override
                public boolean onScale(ScaleGestureDetector detector) {
                    //Log.w(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
                    return false;
                }

            });

    // enable JavaScript for cool things to happen!
    view.getSettings().setJavaScriptEnabled(true);

    // ----- SWIPE PAGE
    view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            /*   if (state == ViewStateEnum.books)
                  swipePage(v, event, 0);
               //int fontSize, newFont;*/
            WebView view = (WebView) v;

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                x1 = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                if (mode != ZOOM && swipeFlag) {
                    //if (state == ViewStateEnum.books)
                    //swipePage(v, event, 0);

                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;

            case MotionEvent.ACTION_MOVE:

                if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        float scale = newDist / oldDist;
                        if (scale > 1) {
                            int currentTextSize = view.getSettings().getTextZoom();
                            textSize = currentTextSize + 15;
                            view.getSettings().setTextZoom(textSize);

                            mode = NONE;
                            swipeFlag = false;
                        } else {
                            int currentTextSize = view.getSettings().getTextZoom();
                            textSize = currentTextSize - 15;
                            view.getSettings().setTextZoom(textSize);
                            mode = NONE;
                            swipeFlag = false;
                        }
                    }
                }
                break;

            }
            return view.onTouchEvent(event);
        }

    });

    // ----- NOTE & LINK
    view.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Message msg = new Message();
            msg.setTarget(new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    String url = msg.getData().getString(getString(R.string.url));

                    if (url != null)
                        navigator.setNote(url, index);
                }
            });
            view.requestFocusNodeHref(msg);

            return false;
        }
    });

    view.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                navigator.setBookPage(url, index);
            } catch (Exception e) {
                errorMessage(getString(R.string.error_LoadPage));
            }
            return true;
        }
    });

    loadPage(viewedPage);
}

From source file:ar.com.tristeslostrestigres.diasporanativewebapp.MainActivity.java

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

    progressBar = findViewById(R.id.progressBar);

    pm = new PrefManager(MainActivity.this);

    SharedPreferences config = getSharedPreferences("PodSettings", MODE_PRIVATE);
    podDomain = config.getString("podDomain", null);

    fab = findViewById(R.id.multiple_actions);
    fab.setVisibility(View.GONE);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from www . j  a  va2 s .co m
    getSupportActionBar().setTitle(null);

    txtTitle = (TextView) findViewById(R.id.toolbar_title);
    txtTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Helpers.isOnline(MainActivity.this)) {
                txtTitle.setText(R.string.jb_stream);
                webView.loadUrl("https://" + podDomain + "/stream");
            } else {
                Snackbar.make(v, R.string.no_internet, Snackbar.LENGTH_SHORT).show();
            }
        }
    });

    webView = findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.addJavascriptInterface(new JavaScriptInterface(), "NotificationCounter");

    if (savedInstanceState != null) {
        webView.restoreState(savedInstanceState);
    }

    wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setUseWideViewPort(true);
    wSettings.setLoadWithOverviewMode(true);
    wSettings.setDomStorageEnabled(true);
    wSettings.setMinimumFontSize(pm.getMinimumFontSize());
    wSettings.setLoadsImagesAutomatically(pm.getLoadImages());

    if (android.os.Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;
        }

        public void onPageFinished(WebView view, String url) {
            if (url.contains("/new") || url.contains("/sign_in")) {
                fab.setVisibility(View.GONE);
            } else {
                fab.setVisibility(View.VISIBLE);
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage(description).setPositiveButton("CLOSE", null).show();
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
                fab.setVisibility(View.VISIBLE);
            }

            if (progress == 100) {
                fab.collapse();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    });

    /*
     * NavigationView
     */
    NavigationView navigationView = findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            drawerLayout.closeDrawers();

            switch (menuItem.getItemId()) {
            default:
                Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                        Snackbar.LENGTH_SHORT).show();
                return true;

            case R.id.jb_stream:
                if (Helpers.isOnline(MainActivity.this)) {
                    txtTitle.setText(R.string.jb_stream);
                    webView.loadUrl("https://" + podDomain + "/stream");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_public:
                setTitle(R.string.jb_public);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/public");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_liked:
                txtTitle.setText(R.string.jb_liked);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/liked");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_commented:
                txtTitle.setText(R.string.jb_commented);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/commented");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_contacts:
                txtTitle.setText(R.string.jb_contacts);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/contacts");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_mentions:
                txtTitle.setText(R.string.jb_mentions);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/mentions");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_activities:
                txtTitle.setText(R.string.jb_activities);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/activity");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_followed_tags:
                txtTitle.setText(R.string.jb_followed_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/followed_tags");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_manage_tags:

                txtTitle.setText(R.string.jb_manage_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/tag_followings/manage");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_license:
                txtTitle.setText(R.string.jb_license);
                new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.license_title))
                        .setMessage(getString(R.string.license_text))
                        .setPositiveButton(getString(R.string.license_yes),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        Intent i = new Intent(Intent.ACTION_VIEW,
                                                Uri.parse("https://github.com/mdev88/Diaspora-Native-WebApp"));
                                        startActivity(i);
                                        dialog.cancel();
                                    }
                                })
                        .setNegativeButton(getString(R.string.license_no),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                })
                        .show();

                return true;

            case R.id.jb_aspects:
                txtTitle.setText(R.string.jb_aspects);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/aspects");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_settings:
                txtTitle.setText(R.string.jb_settings);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/user/edit");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();

                    return false;
                }

            case R.id.jb_pod:
                txtTitle.setText(R.string.jb_pod);
                if (Helpers.isOnline(MainActivity.this)) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.confirmation))
                            .setMessage(getString(R.string.change_pod_warning))
                            .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    webView.clearCache(true);
                                    dialog.cancel();
                                    Intent i = new Intent(MainActivity.this, PodsActivity.class);
                                    startActivity(i);
                                    finish();
                                }
                            }).setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            }).show();
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }
            }
        }
    });

    /*
     * DrawerLayout
     */
    drawerLayout = findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

    if (savedInstanceState == null) {
        if (Helpers.isOnline(MainActivity.this)) {
            webView.loadData("", "text/html", null);
            webView.loadUrl("https://" + podDomain);
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT)
                    .show();
        }
    }

}

From source file:com.ichi2.anki.AbstractFlashcardViewer.java

@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
// because of setDisplayZoomControls.
private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    if (CompatHelper.isHoneycomb()) {
        // Disable the on-screen zoom buttons for API > 11
        webView.getSettings().setDisplayZoomControls(false);
    }//  w  w  w.j  av a2s. co  m
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    // Start at the most zoomed-out level
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    // Problems with focus and input tags is the reason we keep the old type answer mechanism for old Androids.
    webView.setFocusableInTouchMode(mUseInputTag);
    webView.setScrollbarFadingEnabled(true);
    Timber.d("Focusable = %s, Focusable in touch mode = %s", webView.isFocusable(),
            webView.isFocusableInTouchMode());

    webView.setWebViewClient(new WebViewClient() {
        // Filter any links using the custom "playsound" protocol defined in Sound.java.
        // We play sounds through these links when a user taps the sound icon.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("playsound:")) {
                // Send a message that will be handled on the UI thread.
                Message msg = Message.obtain();
                String soundPath = url.replaceFirst("playsound:", "");
                msg.obj = soundPath;
                mHandler.sendMessage(msg);
                return true;
            }
            if (url.startsWith("file") || url.startsWith("data:")) {
                return false; // Let the webview load files, i.e. local images.
            }
            if (url.startsWith("typeblurtext:")) {
                // Store the text the javascript has send us
                mTypeInput = URLDecoder.decode(url.replaceFirst("typeblurtext:", ""));
                //  and show the SHOW ANSWER? button again.
                mFlipCardLayout.setVisibility(View.VISIBLE);
                return true;
            }
            if (url.startsWith("typeentertext:")) {
                // Store the text the javascript has send us
                mTypeInput = URLDecoder.decode(url.replaceFirst("typeentertext:", ""));
                //  and show the answer.
                mFlipCardLayout.performClick();
                return true;
            }
            if (url.equals("signal:typefocus")) {
                // Hide the SHOW ANSWER? button when the input has focus. The soft keyboard takes up enough space
                // by itself.
                mFlipCardLayout.setVisibility(View.GONE);
                return true;
            }
            Timber.d("Opening external link \"%s\" with an Intent", url);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            try {
                startActivityWithoutAnimation(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace(); // Don't crash if the intent is not handled
            }
            return true;
        }

        // Run any post-load events in javascript that rely on the window being completely loaded.
        @Override
        public void onPageFinished(WebView view, String url) {
            Timber.d("onPageFinished triggered");
            view.loadUrl("javascript:onPageFinished();");
        }
    });
    // Set transparent color to prevent flashing white when night mode enabled
    webView.setBackgroundColor(Color.argb(1, 0, 0, 0));
    return webView;
}