Example usage for android.webkit WebViewClient WebViewClient

List of usage examples for android.webkit WebViewClient WebViewClient

Introduction

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

Prototype

WebViewClient

Source Link

Usage

From source file:fr.renzo.wikipoff.ui.activities.ArticleActivity.java

private void showHTML() {
    this.webview.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            String article_title = url;
            if (url.startsWith("file:///")) {
                article_title = url.substring(8);
            }// w  w  w.  j a  v  a  2s  .  c  o m
            try {
                displayNewArticle(URLDecoder.decode(article_title, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return true;
        }
    });

    String data = "<html><head>\n";
    if (this.article != null) {
        setTitle(capitalize(this.article.title));
        data += "<meta name=\"viewport\" content=\"width=device-width,  user-scalable=yes\">\n";
        data += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
        data += "</head>";
        if (config.getBoolean(s(R.string.config_key_use_mathjax), true)) {
            data += "<script type=\"text/javascript\" src=\"" + s(R.string.link_to_mathjax) + "\"></script>\n";
        }
        data += "<body>";
        data += "<h1>" + capitalize(this.article.title) + "</h1>";
        data += this.article.text;

    } else {
        data += getString(R.string.html_message_no_article, wanted_title);
    }
    data += "</body></html>";
    this.webview.loadDataWithBaseURL("file:///android-assets", data, "text/html", "UTF-8", null);
}

From source file:com.ben.gank.fragment.WebFragment.java

private void initWebView() {
    mWebView.setWebViewClient(new WebViewClient() {
        @Override/*w  ww. jav a 2 s.  c  om*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //trueWebViewfalse??
            view.loadUrl(url);
            return true;
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                // ?
                if (mProgressBar != null && mSwipeRefreshLayout != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mProgressBar.setProgress(0);
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            } else {
                // 
                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setDisplayZoomControls(true);

}

From source file:widgets.PageWidget.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    wv = (WebView) super.getActivity().findViewById(activity.getActId());
    // get the location data
    String url = course.getLocation()
            + activity.getLocation(prefs.getString(super.getActivity().getString(R.string.prefs_language),
                    Locale.getDefault().getLanguage()));
    try {/*from w w w.j a  va 2 s .com*/
        wv.loadDataWithBaseURL("file://" + course.getLocation() + "/", FileUtils.readFile(url), "text/html",
                "utf-8", null);
    } catch (IOException e) {
        wv.loadUrl("file://" + url);
    }

    // set up the page to intercept videos
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("/video/")) {
                Log.d(TAG, "Intercepting click on video url: " + url);
                // extract video name from url
                int startPos = url.indexOf("/video/") + 7;
                mediaFileName = url.substring(startPos, url.length());

                // check video file exists
                boolean exists = FileUtils.mediaFileExists(mediaFileName);
                if (!exists) {
                    Toast.makeText(PageWidget.super.getActivity(), PageWidget.super.getActivity()
                            .getString(R.string.error_media_not_found, mediaFileName), Toast.LENGTH_LONG)
                            .show();
                    return true;
                }

                String mimeType = FileUtils.getMimeType(MobileLearning.MEDIA_PATH + mediaFileName);
                if (!FileUtils.supportedMediafileType(mimeType)) {
                    Toast.makeText(PageWidget.super.getActivity(), PageWidget.super.getActivity()
                            .getString(R.string.error_media_unsupported, mediaFileName), Toast.LENGTH_LONG)
                            .show();
                    return true;
                }

                // check user has app installed to play the video
                // launch intent to play video
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                Uri data = Uri.parse(MobileLearning.MEDIA_PATH + mediaFileName);
                intent.setDataAndType(data, "video/mp4");

                PackageManager pm = PageWidget.super.getActivity().getPackageManager();

                List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER);
                boolean appFound = false;
                for (ResolveInfo info : infos) {
                    IntentFilter filter = info.filter;
                    if (filter != null && filter.hasAction(Intent.ACTION_VIEW)) {
                        // Found an app with the right intent/filter
                        appFound = true;
                    }
                }
                if (!appFound) {
                    Toast.makeText(PageWidget.super.getActivity(),
                            PageWidget.super.getActivity().getString(R.string.error_media_app_not_found),
                            Toast.LENGTH_LONG).show();
                    return true;
                }
                PageWidget.this.mediaPlaying = true;
                PageWidget.this.mediaStartTimeStamp = System.currentTimeMillis() / 1000;
                PageWidget.super.getActivity().startActivity(intent);

                return true;
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri data = Uri.parse(url);
                intent.setData(data);
                PageWidget.super.getActivity().startActivity(intent);
                // launch action in mobile browser - not the webview
                // return true so doesn't follow link within webview
                return true;
            }

        }
    });
}

From source file:au.com.wallaceit.reddinator.TabWebFragment.java

@SuppressLint("SetJavaScriptEnabled")
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mContext = this.getActivity();
    if (container == null) {
        return null;
    }/* www . ja v a2s  .  com*/
    if (mFirstTime) {
        // get shared preferences
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
        // work out the url this instance should load
        boolean commentswv = false;
        if (this.getArguments() != null) {
            commentswv = this.getArguments().getBoolean("loadcom", false);
        }

        int fontsize;
        String url;
        if (commentswv) {
            url = "http://reddit.com" + getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_PERMALINK)
                    + ".compact";
            fontsize = Integer.parseInt(prefs.getString("commentfontpref", "22"));
        } else {
            url = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_URL);
            fontsize = Integer.parseInt(prefs.getString("contentfontpref", "18"));
        }
        // setup progressbar
        mActivity = this.getActivity();
        mActivity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        ll = (LinearLayout) inflater.inflate(R.layout.tab1, container, false);
        mWebView = (WebView) ll.findViewById(R.id.webView1);
        // fixes for webview not taking keyboard input on some devices
        mWebView.requestFocus(View.FOCUS_DOWN);
        mWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_UP:
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                    break;
                }
                return false;
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true); // enable ecmascript
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.getSettings().setDefaultFontSize(fontsize);
        mChromeClient = newchromeclient;
        mWebView.setWebChromeClient(mChromeClient);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.loadUrl(url);
        mFirstTime = false;
        //System.out.println("Created fragment");
    } else {
        ((ViewGroup) ll.getParent()).removeView(ll);
    }

    return ll;
}

From source file:com.msopentech.thali.utilities.android.AndroidXmlHttpRequestTestActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    webView = new WebView(this);
    //TODO: Oh, this is all a huge security hole.
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAllowFileAccessFromFileURLs(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().setLoadsImagesAutomatically(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }//from ww w.  j a  v a2  s  . c  o m
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.e("xmlhttptest", "errorCode: " + errorCode + ", description: " + description + ", failingUrl: "
                    + failingUrl);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.e("xmlhttptest", consoleMessage.message() + " - " + consoleMessage.messageLevel().toString()
                    + " - " + consoleMessage.lineNumber() + " - " + consoleMessage.sourceId());
            return false;
        }
    });

    bridgeManager = new AndroidBridgeManager(this, webView);
}

From source file:nya.miku.wishmaster.http.recaptcha.RecaptchaAjax.java

private static String getChallengeInternal(final String address, final String data, CancellableTask task,
        final HttpHost proxy) throws Exception {
    Logger.d(TAG, "not intercepting; proxy: " + (proxy == null ? "disabled" : "enabled"));
    if (proxy != null) {
        Logger.d(TAG, "AJAX recaptcha not using (proxy and old API)");
        throw new Exception("proxy && old API");
        //? ? ? ?  reflection  ???, ..    js-antiddos, ?   ( noscript )
    }//from  w w  w  . j  av  a 2s  .  co m
    final Context context = MainApplication.getInstance();
    final Holder holder = new Holder();

    sHandler.post(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            holder.webView = new WebView(context);
            holder.webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    handler.proceed();
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    String challenge = getChallengeFromImageUrl(url);
                    if (challenge != null)
                        holder.challenge = challenge;
                    super.onLoadResource(view, url);
                }
            });
            holder.webView.getSettings().setUserAgentString(CUSTOM_UA);
            holder.webView.getSettings().setJavaScriptEnabled(true);
            holder.webView.loadDataWithBaseURL(address, data, "text/html", "UTF-8", null);
        }
    });

    long startTime = System.currentTimeMillis();
    while (holder.challenge == null) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT)
            break;
        Thread.yield();
    }

    sHandler.post(new Runnable() {
        @Override
        public void run() {
            try {
                holder.webView.stopLoading();
                holder.webView.clearCache(true);
                holder.webView.destroy();
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }
    });

    if (holder.challenge == null)
        throw new RecaptchaException("couldn't get Recaptcha Challenge (AJAX)");
    return holder.challenge;
}

From source file:com.licubeclub.zionhs.PostViewActivity.java

private void networkTask() {

    final Handler mHandler = new Handler();

    new Thread() {
        public void run() {

            try {
                Document doc = Jsoup.connect(URL).get();
                Element element = doc.select("td").get(4);
                data = element.getAllElements().toString();

            } catch (IOException e) {
                e.printStackTrace();/*  w  w w.j  a  va 2  s  . c  o  m*/
            }

            mHandler.post(new Runnable() {
                public void run() {
                    WV.getSettings().setJavaScriptEnabled(true);
                    WV.setWebViewClient(new WebViewClient() {
                        public void onReceivedError(WebView view, int errorCode, String description,
                                String failingUrl) {
                            Toast.makeText(PostViewActivity.this, description, Toast.LENGTH_SHORT).show();
                        }
                    });
                    //                        WV.loadData(data,"text/html","utf-8");
                    if (data == null) {
                        data = getResources().getString(R.string.nodata);
                    } else if (data.equals("<td class=\"writeBody writeContent\"></td>")) {
                        data = getResources().getString(R.string.nodata);
                    } else {
                    }
                    Log.d("DATA", data);
                    WV.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
                    handler.sendEmptyMessage(0);
                }
            });

        }
    }.start();

}

From source file:com.cw.litenote.operation.import_export.Import_webAct.java

void doCreate() {
    setContentView(R.layout.import_web);

    // web view/*from   w  ww. j  a v  a 2  s.  c  om*/
    webView = (WebView) findViewById(R.id.webView);

    // cancel button
    Button btn_cancel = (Button) findViewById(R.id.import_web_cancel);
    btn_cancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            setResult(RESULT_CANCELED);
            if (webView.canGoBack()) {
                webView.goBack();
                content = null;
            } else
                finish();
        }
    });

    // import button
    btn_import = (Button) findViewById(R.id.import_web_import);
    btn_import.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            setResult(RESULT_OK);

            // import
            // save text in a file
            String dirName = "Download";
            String fileName = "temp.xml";
            String dirPath = Environment.getExternalStorageDirectory().toString() + "/" + dirName;
            File file = new File(dirPath, fileName);

            try {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                if (content != null) {
                    content = content.replaceAll("(?m)^[ \t]*\r?\n", "");
                }
                myOutWriter.append(content);
                myOutWriter.close();

                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                Log.e("Exception", "File write failed: " + e.toString());
            }

            // import file content to DB
            Import_webAct_asyncTask task = new Import_webAct_asyncTask(Import_webAct.this, file.getPath());
            task.enableSaveDB(true);// view
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);

    // create instance
    final ImportInterface import_interface = new ImportInterface(webView);

    // load web content
    webView.addJavascriptInterface(import_interface, "INTERFACE");
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            btn_import.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            System.out.println("Import_webAct / _setWebViewClient / url = " + url);
            view.loadUrl(
                    "javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);");
            if (!url.contains(homeUrl))
                btn_import.setVisibility(View.VISIBLE);
        }

    });

    // show toast
    webView.addJavascriptInterface(import_interface, "LiteNote");

    // load content to web view
    webView.loadUrl(homeUrl);
}

From source file:org.pixmob.fm2.ui.AccountDetailsFragment.java

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

    final View detailsFrame = getActivity().findViewById(R.id.account_details);
    dualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

    setHasOptionsMenu(true);// w ww.  j  a  v a 2 s .  co  m

    webLoadingError = getView().findViewById(R.id.account_web_loading_error);
    webLoadingPanel = getView().findViewById(R.id.account_web_loading_panel);
    webView = (WebView) getView().findViewById(R.id.account_web);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setUserAgentString(HttpUtils.getUserAgent(getActivity()));
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webLoadingPanel.setVisibility(View.GONE);
            webLoadingError.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            webLoadingPanel.setVisibility(View.VISIBLE);
            webLoadingError.setVisibility(View.GONE);
            webView.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webLoadingPanel.setVisibility(View.GONE);
            webLoadingError.setVisibility(View.VISIBLE);
            webView.setVisibility(View.GONE);
        }
    });

    // Authenticate the user in a background task.
    // When authentication cookies are available, the method onLoadFinished
    // will be called, where we can load the account URL.
    getLoaderManager().initLoader(0, getArguments(), this);
}

From source file:com.chatwingsdk.fragments.CommunicationMessagesFragment.java

private void setupWebView() {
    mWebview.setWebViewClient(new WebViewClient() {
        @Override//  w ww .  ja v a  2  s  .  c  o  m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //TODO should be when page start rendering chatbox
            LogUtils.v("Loading page DONE");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.v("Loading page Oh no! " + description);
        }
    });

    mWebview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.v("Loading page " + newProgress + ":" + mWebview);
        }
    });
    WebSettings webSettings = mWebview.getSettings();
    webSettings.setAppCacheEnabled(false);
    webSettings.setJavaScriptEnabled(true);
    mWebview.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);
}