Example usage for android.webkit WebView setWebChromeClient

List of usage examples for android.webkit WebView setWebChromeClient

Introduction

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

Prototype

public void setWebChromeClient(WebChromeClient client) 

Source Link

Document

Sets the chrome handler.

Usage

From source file:com.baidu.cafe.local.record.WebElementRecorder.java

public void setHookedWebChromeClient(final WebView webView) {
    webElementEventCreator.prepareForStart();
    if (webView != null) {
        webView.post(new Runnable() {
            public void run() {
                webView.getSettings().setJavaScriptEnabled(true);
                final WebChromeClient originalWebChromeClient = getOriginalWebChromeClient(webView);
                if (originalWebChromeClient != null) {
                    webView.setWebChromeClient(new WebChromeClient() {
                        HashMap<String, Boolean> invoke = new HashMap<String, Boolean>();

                        /**
                         * Overrides onJsPrompt in order to create
                         * {@code WebElement} objects based on the web
                         * elements attributes prompted by the injections of
                         * JavaScript/*from   w w w. jav a2s.  c  om*/
                         */

                        @Override
                        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                JsPromptResult r) {

                            if (message != null) {
                                if (message.endsWith("WebElementRecorder-finished")) {
                                    // Log.i("onJsPrompt : " + message);
                                    webElementEventCreator.setFinished(true);
                                } else {
                                    webElementEventCreator.createWebElementEvent(message, view);
                                }
                            }
                            r.confirm();
                            return true;
                        }

                        @Override
                        public Bitmap getDefaultVideoPoster() {
                            Bitmap ret = null;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.getDefaultVideoPoster();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public View getVideoLoadingProgressView() {
                            View ret = null;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.getVideoLoadingProgressView();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void getVisitedHistory(ValueCallback<String[]> callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.getVisitedHistory(callback);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onCloseWindow(WebView window) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onCloseWindow(window);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onConsoleMessage(consoleMessage);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                                Message resultMsg) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onCreateWindow(view, isDialog, isUserGesture,
                                        resultMsg);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                                        estimatedDatabaseSize, totalQuota, quotaUpdater);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onGeolocationPermissionsHidePrompt() {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onGeolocationPermissionsHidePrompt();
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onHideCustomView() {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onHideCustomView();
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsAlert(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsBeforeUnload(WebView view, String url, String message,
                                JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsBeforeUnload(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsConfirm(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsTimeout() {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsTimeout();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onProgressChanged(WebView view, int newProgress) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onProgressChanged(view, newProgress);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
                                QuotaUpdater quotaUpdater) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota,
                                        quotaUpdater);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedIcon(WebView view, Bitmap icon) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedIcon(view, icon);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedTitle(WebView view, String title) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedTitle(view, title);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
                                invoke.put(funcName, false);
                            }

                        }

                        @Override
                        public void onRequestFocus(WebView view) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onRequestFocus(view);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onShowCustomView(View view, CustomViewCallback callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onShowCustomView(view, callback);
                                invoke.put(funcName, false);
                            }
                        }

                        public void onShowCustomView(View view, int requestedOrientation,
                                CustomViewCallback callback) {
                            if (Build.VERSION.SDK_INT >= 14) {
                                String funcName = new Throwable().getStackTrace()[1].getMethodName();
                                if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                    invoke.put(funcName, true);
                                    originalWebChromeClient.onShowCustomView(view, requestedOrientation,
                                            callback);
                                    invoke.put(funcName, false);
                                }
                            }
                        }
                    });
                } else {
                    webView.setWebChromeClient(new WebChromeClient() {

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getDefaultVideoPoster()
                         */
                        @Override
                        public Bitmap getDefaultVideoPoster() {
                            // TODO Auto-generated method stub
                            return super.getDefaultVideoPoster();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getVideoLoadingProgressView()
                         */
                        @Override
                        public View getVideoLoadingProgressView() {
                            // TODO Auto-generated method stub
                            return super.getVideoLoadingProgressView();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getVisitedHistory(android.webkit.ValueCallback)
                         */
                        @Override
                        public void getVisitedHistory(ValueCallback<String[]> callback) {
                            // TODO Auto-generated method stub
                            super.getVisitedHistory(callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onCloseWindow(android.webkit.WebView)
                         */
                        @Override
                        public void onCloseWindow(WebView window) {
                            // TODO Auto-generated method stub
                            super.onCloseWindow(window);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)
                         */
                        @Override
                        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                            // TODO Auto-generated method stub
                            return super.onConsoleMessage(consoleMessage);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onConsoleMessage(java.lang.String, int, java.lang.String)
                         */
                        @Override
                        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                            // TODO Auto-generated method stub
                            super.onConsoleMessage(message, lineNumber, sourceID);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onCreateWindow(android.webkit.WebView, boolean, boolean, android.os.Message)
                         */
                        @Override
                        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                                Message resultMsg) {
                            // TODO Auto-generated method stub
                            return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onExceededDatabaseQuota(java.lang.String, java.lang.String, long, long, long, android.webkit.WebStorage.QuotaUpdater)
                         */
                        @Override
                        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
                            // TODO Auto-generated method stub
                            super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize,
                                    totalQuota, quotaUpdater);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onGeolocationPermissionsHidePrompt()
                         */
                        @Override
                        public void onGeolocationPermissionsHidePrompt() {
                            // TODO Auto-generated method stub
                            super.onGeolocationPermissionsHidePrompt();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String, android.webkit.GeolocationPermissions.Callback)
                         */
                        @Override
                        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                            // TODO Auto-generated method stub
                            super.onGeolocationPermissionsShowPrompt(origin, callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onHideCustomView()
                         */
                        @Override
                        public void onHideCustomView() {
                            // TODO Auto-generated method stub
                            super.onHideCustomView();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsAlert(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsAlert(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsBeforeUnload(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsBeforeUnload(WebView view, String url, String message,
                                JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsBeforeUnload(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsConfirm(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsConfirm(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsPrompt(android.webkit.WebView, java.lang.String, java.lang.String, java.lang.String, android.webkit.JsPromptResult)
                         */
                        @Override
                        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                JsPromptResult result) {
                            if (message != null) {
                                if (message.endsWith("WebElementRecorder-finished")) {
                                    // Log.i("onJsPrompt : " + message);
                                    webElementEventCreator.setFinished(true);
                                } else {
                                    webElementEventCreator.createWebElementEvent(message, view);
                                }
                            }
                            result.confirm();
                            return true;
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsTimeout()
                         */
                        @Override
                        public boolean onJsTimeout() {
                            // TODO Auto-generated method stub
                            return super.onJsTimeout();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onProgressChanged(android.webkit.WebView, int)
                         */
                        @Override
                        public void onProgressChanged(WebView view, int newProgress) {
                            // TODO Auto-generated method stub
                            super.onProgressChanged(view, newProgress);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReachedMaxAppCacheSize(long, long, android.webkit.WebStorage.QuotaUpdater)
                         */
                        @Override
                        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
                                QuotaUpdater quotaUpdater) {
                            // TODO Auto-generated method stub
                            super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedIcon(android.webkit.WebView, android.graphics.Bitmap)
                         */
                        @Override
                        public void onReceivedIcon(WebView view, Bitmap icon) {
                            // TODO Auto-generated method stub
                            super.onReceivedIcon(view, icon);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedTitle(android.webkit.WebView, java.lang.String)
                         */
                        @Override
                        public void onReceivedTitle(WebView view, String title) {
                            // TODO Auto-generated method stub
                            super.onReceivedTitle(view, title);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView, java.lang.String, boolean)
                         */
                        @Override
                        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                            // TODO Auto-generated method stub
                            super.onReceivedTouchIconUrl(view, url, precomposed);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onRequestFocus(android.webkit.WebView)
                         */
                        @Override
                        public void onRequestFocus(WebView view) {
                            // TODO Auto-generated method stub
                            super.onRequestFocus(view);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, android.webkit.WebChromeClient.CustomViewCallback)
                         */
                        @Override
                        public void onShowCustomView(View view, CustomViewCallback callback) {
                            // TODO Auto-generated method stub
                            super.onShowCustomView(view, callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, int, android.webkit.WebChromeClient.CustomViewCallback)
                         */
                        @Override
                        public void onShowCustomView(View view, int requestedOrientation,
                                CustomViewCallback callback) {
                            // TODO Auto-generated method stub
                            super.onShowCustomView(view, requestedOrientation, callback);
                        }

                    });
                }
            }
        });
    }
}

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

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

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

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

From source file:com.ichi2.anki2.Reviewer.java

private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    if (mZoomEnabled) {
        webView.getSettings().setBuiltInZoomControls(true);
    }/*ww  w .  j  av a 2 s .  com*/
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    webView.addJavascriptInterface(new JavaScriptInterface(this), "ankidroid");
    if (AnkiDroidApp.SDK_VERSION > 7) {
        webView.setFocusableInTouchMode(false);
    }
    AnkiDroidApp.getCompat().setScrollbarFadingEnabled(webView, mPrefFadeScrollbars);
    Log.i(AnkiDroidApp.TAG, "Focusable = " + webView.isFocusable() + ", Focusable in touch mode = "
            + webView.isFocusableInTouchMode());

    return webView;
}

From source file:com.hichinaschool.flashcards.anki.Reviewer.java

private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    if (mZoomEnabled) {
        webView.getSettings().setBuiltInZoomControls(true);
    }// ww w.  j a  v a2  s . c  o  m
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    webView.addJavascriptInterface(new JavaScriptInterface(this), "ankidroid");
    if (AnkiDroidApp.SDK_VERSION > 7) {
        webView.setFocusableInTouchMode(false);
    }
    AnkiDroidApp.getCompat().setScrollbarFadingEnabled(webView, mPrefFadeScrollbars);
    // Log.i(AnkiDroidApp.TAG, "Focusable = " + webView.isFocusable() + ", Focusable in touch mode = " + webView.isFocusableInTouchMode());

    return webView;
}

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

@Override
public void create() {
    try {//from   w w w.j a v a2s  .  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) {
    }
}