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:Main.java

public static void releaseWebView(WebView webview) {
    webview.stopLoading();//from  w w w  .  j  a v a2 s .  co m
    webview.setWebChromeClient(null);
    webview.setWebViewClient(null);
    webview.destroy();
    webview = null;
}

From source file:de.mkrtchyan.recoverytools.SettingsFragment.java

public static void showChangelog(Context AppContext) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(AppContext);
    dialog.setTitle(R.string.changelog);
    WebView changes = new WebView(AppContext);
    changes.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    changes.setWebViewClient(new WebViewClient());
    changes.loadUrl(Constants.CHANGELOG_URL);
    changes.clearCache(true);//from  w  w  w  .  j a va 2  s .  c o  m
    dialog.setView(changes);
    dialog.show();
}

From source file:com.appnexus.opensdk.ANJAMImplementation.java

private static void callRecordEvent(AdWebView webView, Uri uri) {
    String urlParam = uri.getQueryParameter("url");

    if ((urlParam == null) || (!urlParam.startsWith("http"))) {
        return;/* w  ww  .  j  ava2s. c  o  m*/
    }

    // Create a invisible webview to fire the url
    WebView recordEventWebView = new WebView(webView.getContext());
    recordEventWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Clog.d(Clog.baseLogTag, "RecordEvent completed loading: " + url);

            CookieSyncManager csm = CookieSyncManager.getInstance();
            if (csm != null)
                csm.sync();
        }
    });
    recordEventWebView.loadUrl(urlParam);
    recordEventWebView.setVisibility(View.GONE);
    webView.addView(recordEventWebView);
}

From source file:de.baumann.hhsmoodle.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView) {

    webView.setWebViewClient(new WebViewClient() {

        ProgressDialog progressDialog;/*from  w  w w.  j a  va 2  s.  co m*/
        int numb;

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            ViewPager viewPager = (ViewPager) from.findViewById(R.id.viewpager);
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(from);
            sharedPref.edit().putString("loadURL", webView.getUrl()).apply();

            if (viewPager.getCurrentItem() == 0) {
                if (url != null) {
                    from.setTitle(webView.getTitle());
                }
            }

            if (url != null && url.contains("moodle.huebsch.ka.schule-bw.de/moodle/")
                    && url.contains("/login/")) {

                if (viewPager.getCurrentItem() == 0 && numb != 1) {
                    progressDialog = new ProgressDialog(from);
                    progressDialog.setTitle(from.getString(R.string.login_title));
                    progressDialog.setMessage(from.getString(R.string.login_text));
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                            from.getString(R.string.toast_settings), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    helper_main.switchToActivity(from, Activity_settings.class, true);
                                }
                            });
                    progressDialog.show();
                    numb = 1;
                    progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            numb = 0;
                        }
                    });
                }

            } else if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.cancel();
                numb = 0;
            }

            swipeRefreshLayout.setRefreshing(false);

            class_SecurePreferences sharedPrefSec = new class_SecurePreferences(from, "sharedPrefSec",
                    "Ywn-YM.XK$b:/:&CsL8;=L,y4", true);
            String username = sharedPrefSec.getString("username");
            String password = sharedPrefSec.getString("password");

            final String js = "javascript:" + "document.getElementById('password').value = '" + password + "';"
                    + "document.getElementById('username').value = '" + username + "';"
                    + "var ans = document.getElementsByName('answer');"
                    + "document.getElementById('loginbtn').click()";

            if (Build.VERSION.SDK_INT >= 19) {
                view.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
            } else {
                view.loadUrl(js);
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return handleUri(uri);
        }

        private boolean handleUri(final Uri uri) {
            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }
    });
}

From source file:de.baumann.browser.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView, final EditText editText) {

    webView.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swipeRefreshLayout.setRefreshing(false);
            editText.setText(webView.getTitle());
            if (webView.getTitle() != null && !webView.getTitle().equals("about:blank")) {
                try {
                    final Database_History db = new Database_History(from);
                    db.addBookmark(webView.getTitle(), webView.getUrl());
                    db.close();//from   w w  w .  jav a  2 s  . c o m
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return handleUri(uri);
        }

        private boolean handleUri(final Uri uri) {

            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }

    });
}

From source file:com.prasanna.android.stacknetwork.utils.MarkdownFormatter.java

public static void loadText(final WebView webView, final String text) {
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadDataWithBaseURL(BASE_URL,
            CODE_HTML_PREFIX + MarkdownFormatter.escapeHtml(text) + CODE_HTML_SUFFIX,
            HttpContentTypes.TEXT_HTML, HTTP.UTF_8, null);
}

From source file:im.vector.util.VectorUtils.java

/**
 * Open a webview above the current activity.
 * @param activity the activity//from   w w w . jav a  2  s  .  com
 * @param url the url to open
 */
private static void displayInWebview(final Activity activity, String url) {
    AlertDialog.Builder alert = new AlertDialog.Builder(activity);

    WebView wv = new WebView(activity);
    wv.loadUrl(url);
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            return true;
        }
    });

    alert.setView(wv);
    alert.setPositiveButton(android.R.string.ok, null);
    alert.show();
}

From source file:de.vanita5.twittnuker.fragment.support.BaseSupportWebViewFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final WebView view = getWebView();
    view.setWebViewClient(new DefaultWebViewClient(getActivity()));
    final WebSettings settings = view.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    WebSettingsAccessor.setAllowUniversalAccessFromFileURLs(settings, true);
}

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

public static void showAboutDialog(final Context mContext) {
    LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = li.inflate(R.layout.about, null);

    String sVersionInfo = "";
    try {//from   w  w w. j  ava2 s  .  c o  m
        PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        sVersionInfo += pi.versionName;
        if (!pi.versionName.contains("" + pi.versionCode))
            sVersionInfo += " (" + pi.versionCode + ")";
        if (OpenExplorer.IS_DEBUG_BUILD)
            sVersionInfo += " *debug*";
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String sBuildTime = "";
    try {
        sBuildTime = SimpleDateFormat.getInstance()
                .format(new Date(new ZipFile(
                        mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), 0).sourceDir)
                                .getEntry("classes.dex").getTime()));
    } catch (Exception e) {
        Logger.LogError("Couldn't get Build Time.", e);
    }

    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics dm = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(dm);
    Display d = wm.getDefaultDisplay();
    String sHardwareInfo = "Display:\n";
    sHardwareInfo += "Size: " + d.getWidth() + "x" + d.getHeight() + "\n";
    if (dm != null)
        sHardwareInfo += "Density: " + dm.density + "\n";
    sHardwareInfo += "Rotation: " + d.getRotation() + "\n\n";
    sHardwareInfo += getNetworkInfo(mContext);
    sHardwareInfo += getDeviceInfo();
    ((TextView) view.findViewById(R.id.about_hardware)).setText(sHardwareInfo);

    final String sSubject = "Feedback for OpenExplorer " + sVersionInfo;
    OnClickListener email = new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //intent.addCategory(Intent.CATEGORY_APP_EMAIL);
            intent.putExtra(android.content.Intent.EXTRA_TEXT, "\n" + getDeviceInfo());
            intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "brandroid64@gmail.com" });
            intent.putExtra(android.content.Intent.EXTRA_SUBJECT, sSubject);
            mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.s_chooser_email)));
        }
    };
    OnClickListener viewsite = new OnClickListener() {
        public void onClick(View v) {
            mContext.startActivity(
                    new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://brandroid.org/open/")));
        }
    };
    view.findViewById(R.id.about_email).setOnClickListener(email);
    view.findViewById(R.id.about_email_btn).setOnClickListener(email);
    view.findViewById(R.id.about_site).setOnClickListener(viewsite);
    view.findViewById(R.id.about_site_btn).setOnClickListener(viewsite);
    final View mRecentLabel = view.findViewById(R.id.about_recent_status_label);
    final WebView mRecent = (WebView) view.findViewById(R.id.about_recent);
    final OpenChromeClient occ = new OpenChromeClient();
    occ.mStatus = (TextView) view.findViewById(R.id.about_recent_status);
    mRecent.setWebChromeClient(occ);
    mRecent.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            occ.mStatus.setVisibility(View.GONE);
            mRecent.setVisibility(View.GONE);
            mRecentLabel.setVisibility(View.GONE);
        }
    });
    mRecent.setBackgroundColor(Color.TRANSPARENT);
    mRecent.loadUrl("http://brandroid.org/open/?show=recent");

    ((TextView) view.findViewById(R.id.about_version)).setText(sVersionInfo);
    if (sBuildTime != "")
        ((TextView) view.findViewById(R.id.about_buildtime)).setText(sBuildTime);
    else
        ((TableRow) view.findViewById(R.id.row_buildtime)).setVisibility(View.GONE);

    fillShortcutsTable((TableLayout) view.findViewById(R.id.shortcuts_table));

    final View tab1 = view.findViewById(R.id.tab1);
    final View tab2 = view.findViewById(R.id.tab2);
    final View tab3 = view.findViewById(R.id.tab3);
    ((Button) view.findViewById(R.id.btn_recent)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tab1.setVisibility(View.VISIBLE);
            tab2.setVisibility(View.GONE);
            tab3.setVisibility(View.GONE);
        }
    });
    ((Button) view.findViewById(R.id.btn_hardware)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tab1.setVisibility(View.GONE);
            tab2.setVisibility(View.VISIBLE);
            tab3.setVisibility(View.GONE);
        }
    });
    ((Button) view.findViewById(R.id.btn_shortcuts)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            tab1.setVisibility(View.GONE);
            tab2.setVisibility(View.GONE);
            tab3.setVisibility(View.VISIBLE);
        }
    });

    AlertDialog mDlgAbout = new AlertDialog.Builder(mContext).setTitle(R.string.app_name).setView(view)
            .create();

    mDlgAbout.getWindow().getAttributes().windowAnimations = R.style.SlideDialogAnimation;
    mDlgAbout.getWindow().getAttributes().alpha = 0.9f;

    mDlgAbout.show();
}

From source file:org.gots.ui.WebViewActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    WebView mWebView = new WebView(getActivity());
    mWebView.setWebViewClient(new HelloWebViewClient());
    mWebView.getSettings().setJavaScriptEnabled(true);

    Bundle bundle = this.getArguments();
    String url = bundle.getString("org.gots.seed.url");

    mWebView.loadUrl(url);//from w w w.  j av a 2  s  .  c  om

    pd = ProgressDialog.show(getActivity(), "", getResources().getString(R.string.gots_loading), true);
    pd.setCanceledOnTouchOutside(true);
    return mWebView;
}