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:com.kaltura.playersdk.PlayerViewController.java

/**
 * Build player URL and load it to player view
 * param iFrameUrl- String url//from   w  ww  .ja v  a 2  s .c  om
 */
public void setComponents(String iframeUrl) {
    if (mWebView == null) {
        mWebView = new KControlsView(getContext());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.clearCache(true);
        mWebView.clearHistory();
        mWebView.getSettings().setJavaScriptEnabled(true);
        //mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.setKControlsViewClient(this);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mWebView.setBackgroundColor(0);
        mCurSec = 0;
        ViewGroup.LayoutParams currLP = getLayoutParams();
        LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height);

        this.playerController = new KPlayerController(new KPlayer(mActivity), this);
        this.playerController.addPlayerToController(this);
        this.addView(mWebView, wvLp);
    }
    iframeUrl = RequestHandler.getIframeUrlWithNativeVersion(iframeUrl, this.getContext());
    if (mIframeUrl == null || !mIframeUrl.equals(iframeUrl)) {
        iframeUrl = iframeUrl + "&iframeembed=true";
        mIframeUrl = iframeUrl;
        mWebView.loadUrl(iframeUrl);
    }
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void trySetupContentView() {
    mContentView.setVerticalScrollBarEnabled(false);
    mContentView.setHorizontalScrollBarEnabled(false);
    mContentView.getSettings().setJavaScriptEnabled(true);

    mContentView.setWebChromeClient(new WebChromeClient() {
        @Override/*  w w w .ja v  a  2  s. co m*/
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            Log.d(TAG, "newProgress = [" + newProgress + "]");
        }
    });

    mContentView.addJavascriptInterface(this, "Attiq");
    mContentView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (!mIsFirstTimeLoaded && mLoadingView != null) {
                mLoadingView.setAlpha(1.f);
                mLoadingView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            if (PrefUtil.isMathJaxEnabled()) {
                view.evaluateJavascript("javascript:document.getElementById('content').innerHTML='"
                        + doubleEscapeTeX(mArticle.getRenderedBody()) + "';", null);
                view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);",
                        new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                view.loadUrl("javascript:(function () "
                                        + "{document.getElementsByTagName('body')[0].style.marginBottom = '0'})()");
                            }
                        });
            }

            mIsFirstTimeLoaded = true;
            if (mLoadingView != null) {
                ViewCompat.animate(mLoadingView).alpha(0.f).setDuration(300)
                        .setListener(new ViewPropertyAnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(View view) {
                                if (mLoadingView != null) {
                                    mLoadingView.setVisibility(View.GONE);
                                }
                            }
                        }).start();
            }
        }
    });

    mContentView.setFindListener(new WebView.FindListener() {
        @Override
        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
            if (mMenuLayout != null) {
                mMenuLayout.closeDrawer(GravityCompat.END);
            }
            if (numberOfMatches > 0 && mMenuAnchor != null && mContentView != null) {
                // FIXME Doesn't work now, because WebView is staying inside ScrollView
                mContentView.loadUrl("javascript:scrollToElement(\"" + mMenuAnchor.text() + "\");");
            }
        }
    });
}

From source file:com.agustinprats.myhrv.fragment.MonitorFragment.java

/** Displays help to the user. */
private void showHelp() {

    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
    alert.setTitle(getActivity().getString(R.string.Help));

    WebView wv = new WebView(getActivity());

    // loading the html file
    String htmlData = readAsset("help.html");

    // selecting the css based on the activity theme
    //        htmlData = htmlData.replaceFirst("CSS_FILE_NAME", ((MainActivity) getActivity()).isLightTheme() ? "light" : "dark");
    htmlData = htmlData.replaceFirst("CSS_FILE_NAME", "dark");
    // loading html in the webview
    wv.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

    wv.setWebViewClient(new WebViewClient() {
        @Override//  w  ww  . ja v  a 2  s . c  om
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    alert.setView(wv);
    alert.setNegativeButton(getActivity().getString(R.string.Close), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    alert.show();
}

From source file:com.openatk.rockapp.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = false;

    switch (item.getItemId()) {
    case R.id.add:
        addRock();//from w  w w  .ja va2  s  .c o m
        result = true;
        break;

    case R.id.gps:
        Location myLoc = map.getMyLocation();
        if (myLoc == null) {
            Toast.makeText(this, R.string.location_wait, Toast.LENGTH_SHORT).show();
        } else {
            CameraPosition oldPos = map.getCameraPosition();
            CameraPosition newPos = new CameraPosition(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()),
                    map.getMaxZoomLevel(), oldPos.tilt, oldPos.bearing);
            map.animateCamera(CameraUpdateFactory.newCameraPosition(newPos));
        }
        result = true;
        break;

    case R.id.all_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_BOTH);
        result = true;
        break;

    case R.id.not_picked_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_NOT_PICKED_UP);
        result = true;
        break;

    case R.id.picked_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_PICKED_UP);
        result = true;
        break;

    case R.id.list:
        // showRockList();
        result = true;
        break;

    case R.id.rock_delete:
        showConfirmRockDeleteAlert();
        result = true;
        break;

    case R.id.rock_undo_move:
        undoRockMove();
        result = true;
        break;

    case R.id.sync:
        //Tell trello app to sync
        TrelloContentProvider.Sync(this.getApplicationContext().getPackageName());
        result = true;
        break;
    case R.id.menu_help:
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Help");
        WebView wv = new WebView(this);
        wv.loadUrl("file:///android_asset/Help.html");
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        alert.setView(wv);
        alert.setNegativeButton("Close", null);
        alert.show();
        break;
    case R.id.menu_legal:
        CharSequence licence = "The MIT License (MIT)\n" + "\n" + "Copyright (c) 2013 Purdue University\n"
                + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy "
                + "of this software and associated documentation files (the \"Software\"), to deal "
                + "in the Software without restriction, including without limitation the rights "
                + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "
                + "copies of the Software, and to permit persons to whom the Software is "
                + "furnished to do so, subject to the following conditions:" + "\n"
                + "The above copyright notice and this permission notice shall be included in "
                + "all copies or substantial portions of the Software.\n" + "\n"
                + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "
                + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "
                + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "
                + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "
                + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, "
                + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN "
                + "THE SOFTWARE.\n";
        new AlertDialog.Builder(this).setTitle("Legal").setMessage(licence)
                .setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Close", null).show();
        break;
    }

    // If we didn't handle, let the super version try
    return result | super.onOptionsItemSelected(item);
}

From source file:com.pindroid.fragment.ViewBookmarkFragment.java

private void showInWebView(String url) {
    String readingBackground = SettingsHelper.getReadingBackground(getActivity());
    String readingFont = SettingsHelper.getReadingFont(getActivity());
    String readingFontSize = SettingsHelper.getReadingFontSize(getActivity());
    String readingMargins = SettingsHelper.getReadingMargins(getActivity());

    mWebContent.loadUrl("about:blank");
    mWebContent.clearCache(true);/* w  w  w .  j a  v a  2  s .c  o m*/

    CookieManager cookieManager = CookieManager.getInstance();
    CookieSyncManager.createInstance(getActivity());

    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie("http://www.instapaper.com",
            "iptcolor=" + readingBackground + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptfont=" + readingFont + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptsize=" + readingFontSize + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptwidth=" + readingMargins + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");

    CookieSyncManager.getInstance().sync();

    mWebContent.setWebViewClient(new WebViewClient() {
    });

    mWebContent.loadUrl(url);
}

From source file:com.cw.litenote.note.Note_adapter.java

@Override
public void setPrimaryItem(final ViewGroup container, int position, Object object) {
    // set primary item only
    if (mLastPosition != position) {
        System.out.println("Note_adapter / _setPrimaryItem / mLastPosition = " + mLastPosition);
        System.out.println("Note_adapter / _setPrimaryItem / position = " + position);

        String lastPictureStr = null;
        String lastLinkUri = null;
        String lastAudioUri = null;

        if (mLastPosition != -1) {
            lastPictureStr = db_page.getNotePictureUri(mLastPosition, true);
            lastLinkUri = db_page.getNoteLinkUri(mLastPosition, true);
            lastAudioUri = db_page.getNoteAudioUri(mLastPosition, true);
        }/*w w w .j ava  2 s.com*/

        String pictureStr = db_page.getNotePictureUri(position, true);
        String linkUri = db_page.getNoteLinkUri(position, true);
        String audioUri = db_page.getNoteAudioUri(position, true);

        // remove last text web view
        if (!Note.isPictureMode()) {
            String tag = "current" + mLastPosition + "textWebView";
            CustomWebView textWebView = (CustomWebView) pager.findViewWithTag(tag);
            if (textWebView != null) {
                textWebView.onPause();
                textWebView.onResume();
            }
        }

        // for web view
        if (!UtilImage.hasImageExtension(pictureStr, act) && !UtilVideo.hasVideoExtension(pictureStr, act)) {
            // remove last link web view
            if (!UtilImage.hasImageExtension(lastPictureStr, act)
                    && !UtilVideo.hasVideoExtension(lastPictureStr, act)
                    && !UtilAudio.hasAudioExtension(lastAudioUri) && !Util.isYouTubeLink(lastLinkUri)) {
                String tag = "current" + mLastPosition + "linkWebView";
                CustomWebView lastLinkWebView = (CustomWebView) pager.findViewWithTag(tag);

                if (lastLinkWebView != null) {
                    CustomWebView.pauseWebView(lastLinkWebView);
                    CustomWebView.blankWebView(lastLinkWebView);
                }
            }

            // set current link web view in case no picture Uri
            if (Util.isEmptyString(pictureStr) && !Util.isYouTubeLink(linkUri) && linkUri.startsWith("http")
                    && !Note.isTextMode()) {
                if (Note.isViewAllMode()) {
                    String tagStr = "current" + position + "linkWebView";
                    CustomWebView linkWebView = (CustomWebView) pager.findViewWithTag(tagStr);
                    linkWebView.setVisibility(View.VISIBLE);
                    setWebView(linkWebView, object, CustomWebView.LINK_VIEW);
                    System.out.println("Note_adapter / _setPrimaryItem / load linkUri = " + linkUri);
                    linkWebView.loadUrl(linkUri);

                    //Add for non-stop showing of full screen web view
                    linkWebView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return true;
                        }
                    });

                    //cf. https://stackoverflow.com/questions/13576153/how-to-get-text-from-a-webview
                    //                  linkWebView.addJavascriptInterface(new JavaScriptInterface(act), "Android");
                } else if (Note.isPictureMode()) {
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUri));
                    act.startActivity(i);
                }
            }
        }

        // for video view
        if (!Note.isTextMode()) {

            // stop last video view running
            if (mLastPosition != -1) {
                String tagVideoStr = "current" + mLastPosition + "videoView";
                VideoViewCustom lastVideoView = (VideoViewCustom) pager.findViewWithTag(tagVideoStr);
                lastVideoView.stopPlayback();
            }

            // Show picture view UI
            if (Note.isViewAllMode() || Note.isPictureMode()) {
                NoteUi.cancel_UI_callbacks();
                picUI_primary = new NoteUi(act, pager, position);
                picUI_primary.tempShow_picViewUI(5002, pictureStr);
            }

            // Set video view
            if (UtilVideo.hasVideoExtension(pictureStr, act) && !UtilImage.hasImageExtension(pictureStr, act)) {
                // update current pager view
                UtilVideo.mCurrentPagerView = (View) object;

                // for view mode change
                if (Note.mIsViewModeChanged && (Note.mPlayVideoPositionOfInstance == 0)) {
                    UtilVideo.mPlayVideoPosition = Note.mPositionOfChangeView;
                    UtilVideo.setVideoViewLayout(pictureStr);

                    if (UtilVideo.mPlayVideoPosition > 0)
                        UtilVideo.playOrPauseVideo(pager, pictureStr);
                } else {
                    // for key protect
                    if (Note.mPlayVideoPositionOfInstance > 0) {
                        UtilVideo.setVideoState(UtilVideo.VIDEO_AT_PAUSE);
                        UtilVideo.setVideoViewLayout(pictureStr);

                        if (!UtilVideo.hasMediaControlWidget) {
                            NoteUi.updateVideoPlayButtonState(pager, NoteUi.getFocus_notePos());
                            picUI_primary.tempShow_picViewUI(5003, pictureStr);
                        }

                        UtilVideo.playOrPauseVideo(pager, pictureStr);
                    } else {
                        if (UtilVideo.hasMediaControlWidget)
                            UtilVideo.setVideoState(UtilVideo.VIDEO_AT_PLAY);
                        else
                            UtilVideo.setVideoState(UtilVideo.VIDEO_AT_STOP);

                        UtilVideo.mPlayVideoPosition = 0; // make sure play video position is 0 after page is changed
                        UtilVideo.initVideoView(pager, pictureStr, act, position);
                    }
                }

                UtilVideo.currentPicturePath = pictureStr;
            }
        }

        ViewGroup audioBlock = (ViewGroup) act.findViewById(R.id.audioGroup);
        audioBlock.setVisibility(View.VISIBLE);

        // init audio block of pager
        if (UtilAudio.hasAudioExtension(audioUri)
                || UtilAudio.hasAudioExtension(Util.getDisplayNameByUriString(audioUri, act))) {
            AudioUi_note.initAudioProgress(act, audioUri, pager);

            if (Audio_manager.getAudioPlayMode() == Audio_manager.NOTE_PLAY_MODE) {
                if (Audio_manager.getPlayerState() != Audio_manager.PLAYER_AT_STOP)
                    AudioUi_note.updateAudioProgress(act);
            }

            AudioUi_note.updateAudioPlayState(act);
        } else
            audioBlock.setVisibility(View.GONE);
    }
    mLastPosition = position;

}

From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(Context context) {
    if (context instanceof Activity) {
        mActivity = new WeakReference<>((Activity) context);
    }/*from ww w . j ava2s .  c o m*/

    mLanguageIso3 = getLanguageIso3();

    setFocusable(true);
    setFocusableInTouchMode(true);

    setSaveEnabled(true);

    final String filesDir = context.getFilesDir().getPath();
    final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER;

    final WebSettings webSettings = getSettings();
    webSettings.setAllowFileAccess(false);
    setAllowAccessFromFileUrls(webSettings, false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    if (Build.VERSION.SDK_INT < 18) {
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    webSettings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT < 19) {
        webSettings.setDatabasePath(databaseDir);
    }
    setMixedContentAllowed(webSettings, true);

    setThirdPartyCookiesEnabled(true);

    super.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageStarted(url, favicon);
                }
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageFinished(url);
                }
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageFinished(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            setLastError();

            if (mListener != null) {
                mListener.onPageError(errorCode, description, failingUrl);
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl);
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (isHostnameAllowed(url)) {
                return mCustomWebViewClient != null && mCustomWebViewClient.shouldOverrideUrlLoading(view, url);
            } else {
                if (mListener != null) {
                    mListener.onExternalPageRequest(url);
                }

                return true;
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onLoadResource(view, url);
            } else {
                super.onLoadResource(view, url);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (Build.VERSION.SDK_INT >= 11) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, url);
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            } else {
                return null;
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, request);
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            } else {
                return null;
            }
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onFormResubmission(view, dontResend, resend);
            } else {
                super.onFormResubmission(view, dontResend, resend);
            }
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload);
            } else {
                super.doUpdateVisitedHistory(view, url, isReload);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedSslError(view, handler, error);
            } else {
                super.onReceivedSslError(view, handler, error);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedClientCertRequest(view, request);
                } else {
                    super.onReceivedClientCertRequest(view, request);
                }
            }
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
                String realm) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm);
            } else {
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                return mCustomWebViewClient.shouldOverrideKeyEvent(view, event);
            } else {
                return super.shouldOverrideKeyEvent(view, event);
            }
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onUnhandledKeyEvent(view, event);
            } else {
                super.onUnhandledKeyEvent(view, event);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onUnhandledInputEvent(WebView view, InputEvent event) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onUnhandledInputEvent(view, event);
                } else {
                    super.onUnhandledInputEvent(view, event);
                }
            }
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onScaleChanged(view, oldScale, newScale);
            } else {
                super.onScaleChanged(view, oldScale, newScale);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (Build.VERSION.SDK_INT >= 12) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args);
                } else {
                    super.onReceivedLoginRequest(view, realm, account, args);
                }
            }
        }

    });

    super.setWebChromeClient(new WebChromeClient() {

        // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }

        // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, acceptType, null);
        }

        // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileInput(uploadMsg, null);
        }

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            openFileInput(null, filePathCallback);
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onProgressChanged(view, newProgress);
            } else {
                super.onProgressChanged(view, newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTitle(view, title);
            } else {
                super.onReceivedTitle(view, title);
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedIcon(view, icon);
            } else {
                super.onReceivedIcon(view, icon);
            }
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
            } else {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onShowCustomView(view, callback);
            } else {
                super.onShowCustomView(view, callback);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (Build.VERSION.SDK_INT >= 14) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback);
                } else {
                    super.onShowCustomView(view, requestedOrientation, callback);
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onHideCustomView();
            } else {
                super.onHideCustomView();
            }
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                Message resultMsg) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            } else {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onRequestFocus(view);
            } else {
                super.onRequestFocus(view);
            }
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onCloseWindow(window);
            } else {
                super.onCloseWindow(window);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsAlert(view, url, message, result);
            } else {
                return super.onJsAlert(view, url, message, result);
            }
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsConfirm(view, url, message, result);
            } else {
                return super.onJsConfirm(view, url, message, result);
            }
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                JsPromptResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result);
            } else {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result);
            } else {
                return super.onJsBeforeUnload(view, url, message, result);
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            if (mGeolocationEnabled) {
                callback.invoke(origin, true, false);
            } else {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                } else {
                    super.onGeolocationPermissionsShowPrompt(origin, callback);
                }
            }
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onGeolocationPermissionsHidePrompt();
            } else {
                super.onGeolocationPermissionsHidePrompt();
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequest(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequest(request);
                } else {
                    super.onPermissionRequest(request);
                }
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequestCanceled(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequestCanceled(request);
                } else {
                    super.onPermissionRequestCanceled(request);
                }
            }
        }

        @Override
        public boolean onJsTimeout() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsTimeout();
            } else {
                return super.onJsTimeout();
            }
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
            } else {
                super.onConsoleMessage(message, lineNumber, sourceID);
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onConsoleMessage(consoleMessage);
            } else {
                return super.onConsoleMessage(consoleMessage);
            }
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getDefaultVideoPoster();
            } else {
                return super.getDefaultVideoPoster();
            }
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getVideoLoadingProgressView();
            } else {
                return super.getVideoLoadingProgressView();
            }
        }

        @Override
        public void getVisitedHistory(ValueCallback<String[]> callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.getVisitedHistory(callback);
            } else {
                super.getVisitedHistory(callback);
            }
        }

        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                        estimatedDatabaseSize, totalQuota, quotaUpdater);
            } else {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota,
                        quotaUpdater);
            }
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            } else {
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }
        }

    });

    setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            if (mListener != null) {
                mListener.onDownloadRequested(url, userAgent, contentDisposition, mimetype, contentLength);
            }
        }

    });
}

From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java

/**
 * Closes the dialog//  ww  w .j  a va2s  .  co  m
 */
public void closeDialog() {
    final WebView childView = this.inAppWebView;
    // The JS protects against multiple calls, so this should happen only when
    // closeDialog() is called by other native code.
    if (childView == null) {
        return;
    }
    this.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            childView.setWebViewClient(new WebViewClient() {
                // NB: wait for about:blank before dismissing
                public void onPageFinished(WebView view, String url) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
            // NB: From SDK 19: "If you call methods on WebView from any thread
            // other than your app's UI thread, it can cause unexpected results."
            // http://developer.android.com/guide/webapps/migrating.html#Threads
            childView.loadUrl("about:blank");
        }
    });

    try {
        JSONObject obj = new JSONObject();
        obj.put("type", EXIT_EVENT);
        sendUpdate(obj, false);
    } catch (JSONException ex) {
        Log.d(LOG_TAG, "Should never happen");
    }
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

@Override
public void create() {
    try {//  w w  w .j  av a  2s.c  om

        setContentView(R.layout.romanblack_html_main);
        root = (FrameLayout) findViewById(R.id.romanblack_root_layout);
        webView = new ObservableWebView(this);
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        root.addView(webView);

        webView.setHorizontalScrollBarEnabled(false);
        setTitle("HTML");

        Intent currentIntent = getIntent();
        Bundle store = currentIntent.getExtras();
        widget = (Widget) store.getSerializable("Widget");
        if (widget == null) {
            handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
            return;
        }
        appName = widget.getAppName();

        if (widget.getPluginXmlData().length() == 0) {
            if (currentIntent.getStringExtra("WidgetFile").length() == 0) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
                return;
            }
        }

        if (widget.getTitle() != null && widget.getTitle().length() > 0) {
            setTopBarTitle(widget.getTitle());
        } else {
            setTopBarTitle(getResources().getString(R.string.romanblack_html_web));
        }

        currentUrl = (String) getSession();
        if (currentUrl == null) {
            currentUrl = "";
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            isOnline = true;
        }

        // topbar initialization
        setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (isOnline) {
            webView.getSettings().setJavaScriptEnabled(true);
        }

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setSavePassword(false);
        webView.clearHistory();
        webView.invalidate();

        if (Build.VERSION.SDK_INT >= 19) {
        }
        webView.getSettings().setUserAgentString(
                "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.invalidate();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                }
                    break;
                case MotionEvent.ACTION_UP: {
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                }
                    break;

                case MotionEvent.ACTION_MOVE: {
                }
                    break;

                }
                return false;
            }
        });

        webView.setBackgroundColor(Color.WHITE);
        try {
            if (widget.getBackgroundColor() != Color.TRANSPARENT) {
                webView.setBackgroundColor(widget.getBackgroundColor());
            }
        } catch (IllegalArgumentException e) {
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                    final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setTitle(R.string.location_dialog_title);
                builder.setMessage(R.string.location_dialog_description);
                builder.setCancelable(true);

                builder.setPositiveButton(R.string.location_dialog_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, true, false);
                            }
                        });

                builder.setNegativeButton(R.string.location_dialog_not_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, false, false);
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                if (customView != null) {
                    customViewCallback.onCustomViewHidden();
                    return;
                }

                view.setBackgroundColor(Color.BLACK);
                view.setLayoutParams(LayoutParameters);
                root.addView(view);
                customView = view;
                customViewCallback = callback;
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onHideCustomView() {
                if (customView == null) {
                    return;
                } else {
                    closeFullScreenVideo();
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                isMedia = true;
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                isMedia = true;
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                isV21 = true;
                mUploadMessageV21 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (state == states.EMPTY) {
                    currentUrl = url;
                    setSession(currentUrl);
                    state = states.LOAD_START;
                    handler.sendEmptyMessage(SHOW_PROGRESS);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                if (!alreadyLoaded
                        && (url.startsWith("http://www.youtube.com/get_video_info?")
                                || url.startsWith("https://www.youtube.com/get_video_info?"))
                        && Build.VERSION.SDK_INT < 11) {
                    try {
                        String path = url.contains("https://www.youtube.com/get_video_info?")
                                ? url.replace("https://www.youtube.com/get_video_info?", "")
                                : url.replace("http://www.youtube.com/get_video_info?", "");

                        String[] parqamValuePairs = path.split("&");

                        String videoId = null;

                        for (String pair : parqamValuePairs) {
                            if (pair.startsWith("video_id")) {
                                videoId = pair.split("=")[1];
                                break;
                            }
                        }

                        if (videoId != null) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                    .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                            needRefresh = true;
                            alreadyLoaded = !alreadyLoaded;

                            return;
                        }
                    } catch (Exception ex) {
                    }
                } else {
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (hideProgress) {
                    if (TextUtils.isEmpty(WebPlugin.this.url)) {
                        state = states.LOAD_COMPLETE;
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        super.onPageFinished(view, url);
                    } else {
                        view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');"
                                + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);"
                                + "l.dispatchEvent(e);" + "})()");
                        hideProgress = false;
                    }
                } else {
                    state = states.LOAD_COMPLETE;
                    handler.sendEmptyMessage(HIDE_PROGRESS);
                    super.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (errorCode == WebViewClient.ERROR_BAD_URL) {
                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                            DOWNLOAD_REQUEST_CODE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.proceed();
                            }
                        });
                builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.cancel();
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {

                    if (url.contains("youtube.com/watch")) {
                        if (Build.VERSION.SDK_INT < 11) {
                            try {
                                startActivity(
                                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                                .setData(Uri.parse(url)));
                                return true;
                            } catch (Exception ex) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else if (url.contains("paypal.com")) {
                        if (url.contains("&bn=ibuildapp_SP")) {
                            return false;
                        } else {
                            url = url + "&bn=ibuildapp_SP";

                            webView.loadUrl(url);

                            return true;
                        }
                    } else if (url.contains("sms:")) {
                        try {
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(url));
                            startActivity(smsIntent);
                            return true;
                        } catch (Exception ex) {
                            Log.e("", ex.getMessage());
                            return false;
                        }
                    } else if (url.contains("tel:")) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse(url));
                        startActivity(callIntent);
                        return true;
                    } else if (url.contains("mailto:")) {
                        MailTo mailTo = MailTo.parse(url);

                        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                        emailIntent.setType("plain/text");
                        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                new String[] { mailTo.getTo() });

                        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject());
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody());
                        WebPlugin.this.startActivity(Intent.createChooser(emailIntent,
                                getString(R.string.romanblack_html_send_email)));
                        return true;
                    } else if (url.contains("rtsp:")) {
                        Uri address = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, address);

                        final PackageManager pm = getPackageManager();
                        final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0);
                        if (matches.size() > 0) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player),
                                    Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    } else if (url.startsWith("intent:") || url.startsWith("market:")
                            || url.startsWith("col-g2m-2:")) {
                        Intent it = new Intent();
                        it.setData(Uri.parse(url));
                        startActivity(it);

                        return true;
                    } else if (url.contains("//play.google.com/")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else {
                        if (url.contains("ibuildapp.com-1915109")) {
                            String param = Uri.parse(url).getQueryParameter("widget");
                            finish();
                            if (param != null && param.equals("1001"))
                                com.appbuilder.sdk.android.Statics.launchMain();
                            else if (param != null && !"".equals(param)) {
                                View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param));
                                if (widget != null)
                                    widget.onClick(view);
                            }
                            return false;
                        }

                        currentUrl = url;
                        setSession(currentUrl);
                        if (!isOnline) {
                            handler.sendEmptyMessage(HIDE_PROGRESS);
                            handler.sendEmptyMessage(STOP_LOADING);
                        } else {
                            String pageType = "application/html";
                            if (!url.contains("vk.com")) {
                                getPageType(url);
                            }
                            if (pageType.contains("application") && !pageType.contains("html")
                                    && !pageType.contains("xml")) {
                                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                                        DOWNLOAD_REQUEST_CODE);
                                return super.shouldOverrideUrlLoading(view, url);
                            } else {
                                view.getSettings().setLoadWithOverviewMode(true);
                                view.getSettings().setUseWideViewPort(true);
                                view.setBackgroundColor(Color.WHITE);
                            }
                        }
                        return false;
                    }

                } catch (Exception ex) { // Error Logging
                    return false;
                }
            }
        });

        handler.sendEmptyMessage(SHOW_PROGRESS);

        new Thread() {
            @Override
            public void run() {

                EntityParser parser;
                if (widget.getPluginXmlData() != null) {
                    if (widget.getPluginXmlData().length() > 0) {
                        parser = new EntityParser(widget.getPluginXmlData());
                    } else {
                        String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                        parser = new EntityParser(xmlData);
                    }
                } else {
                    String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                    parser = new EntityParser(xmlData);
                }

                parser.parse();

                url = parser.getUrl();
                html = parser.getHtml();

                if (url.length() > 0 && !isOnline) {
                    handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
                } else {
                    if (isOnline) {
                    } else {
                        if (html.length() == 0) {
                        }
                    }
                    if (html.length() > 0 || url.length() > 0) {
                        handler.sendEmptyMessageDelayed(SHOW_HTML, 700);
                    } else {
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        handler.sendEmptyMessage(INITIALIZATION_FAILED);
                    }
                }
            }
        }.start();

    } catch (Exception ex) {
    }
}

From source file:com.mobicage.rogerthat.plugins.messaging.AttachmentViewerActivity.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void updateView(boolean isUpdate) {
    T.UI();/* w ww .ja v a  2s.  co  m*/

    if (!isUpdate && mGenerateThumbnail) {
        File thumbnail = new File(mFile.getAbsolutePath() + ".thumb");
        if (!thumbnail.exists()) {
            boolean isImage = mContentType.toLowerCase(Locale.US).startsWith("image/");
            boolean isVideo = !isImage && mContentType.toLowerCase(Locale.US).startsWith("video/");
            try {
                // Try to generate a thumbnail
                mMessagingPlugin.createAttachmentThumbnail(mFile.getAbsolutePath(), isImage, isVideo);
            } catch (Exception e) {
                L.e("Failed to generate attachment thumbnail", e);
            }
        }
    }

    final String fileOnDisk = "file://" + mFile.getAbsolutePath();

    if (mContentType.toLowerCase(Locale.US).startsWith("video/")) {
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoview);

        Uri video = Uri.parse(fileOnDisk);
        mVideoview.setMediaController(mediacontroller);
        mVideoview.setVideoURI(video);

        mVideoview.requestFocus();
        mVideoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoview.start();
            }
        });

        mVideoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                L.e("Could not play video, what " + what + ", extra " + extra + ", content_type " + mContentType
                        + ", and url " + mDownloadUrl);

                AlertDialog.Builder builder = new AlertDialog.Builder(AttachmentViewerActivity.this);
                builder.setMessage(R.string.error_please_try_again);
                builder.setCancelable(true);
                builder.setTitle(null);
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.setPositiveButton(R.string.rogerthat, new SafeDialogInterfaceOnClickListener() {
                    @Override
                    public void safeOnClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.create().show();
                return true;
            }
        });

    } else if (CONTENT_TYPE_PDF.equalsIgnoreCase(mContentType)) {
        WebSettings settings = mWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }

        mWebview.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (fileOnDisk.equals(url)) {
                    return null;
                }
                L.d("404: Expected: '" + fileOnDisk + "'\n Received: '" + url + "'");
                return new WebResourceResponse("text/plain", "UTF-8", null);
            }
        });
        try {
            mWebview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file="
                    + URLEncoder.encode(fileOnDisk, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            L.bug(uee);
        }
    } else {
        WebSettings settings = mWebview.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
        }
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);

        if (mContentType.toLowerCase(Locale.US).startsWith("image/")) {
            String html = "<html><head></head><body><img style=\"width: 100%;\" src=\"" + fileOnDisk
                    + "\"></body></html>";
            mWebview.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
        } else {
            mWebview.loadUrl(fileOnDisk);
        }
    }
    L.d("File on disk: " + fileOnDisk);
}