Example usage for android.webkit WebView loadUrl

List of usage examples for android.webkit WebView loadUrl

Introduction

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

Prototype

public void loadUrl(String url) 

Source Link

Document

Loads the given URL.

Usage

From source file:in.ac.dtu.subtlenews.InstapaperViewer.java

@SuppressLint("NewApi")
@Override/*from   w w  w.  jav  a2  s  . co  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setImmersive(true);
    }
    setTheme(R.style.AppTheme_NoActionBar);

    setContentView(R.layout.activity_instapaper_viewer);
    //setupActionBar();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        urlId = extras.getInt("URLID");
        urlList = extras.getStringArrayList("URLList");

    }
    final WebView instapaperView = (WebView) findViewById(R.id.instapaper_viewer);
    final Activity activity = this;
    final ProgressBar progressBar;
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    instapaperView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
                progressBar.setVisibility(ProgressBar.VISIBLE);
                //txtview.setVisibility(View.VISIBLE);
            }
            progressBar.setProgress(progress);
            if (progress == 100) {
                progressBar.setVisibility(ProgressBar.GONE);
                //txtview.setVisibility(View.GONE);
            }
        }
    });

    final View controlsView = findViewById(R.id.fullscreen_content_controls);
    final View contentView = findViewById(R.id.instapaper_viewer);

    final Button prevButton = (Button) findViewById(R.id.summary_prev_button);
    final Button nextButton = (Button) findViewById(R.id.summary_next_button);

    // Set up an instance of SystemUiHider to control the system UI for
    // this activity.
    mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
    mSystemUiHider.setup();
    mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
        // Cached values.
        int mControlsHeight;
        int mShortAnimTime;

        @Override
        @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
        public void onVisibilityChange(boolean visible) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                // If the ViewPropertyAnimator API is available
                // (Honeycomb MR2 and later), use it to animate the
                // in-layout UI controls at the bottom of the
                // screen.
                if (mControlsHeight == 0) {
                    mControlsHeight = controlsView.getHeight();
                }
                if (mShortAnimTime == 0) {
                    mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
                }
                controlsView.animate().translationY(visible ? 0 : mControlsHeight).setDuration(mShortAnimTime);
            } else {
                // If the ViewPropertyAnimator APIs aren't
                // available, simply show or hide the in-layout UI
                // controls.
                controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
            }

            if (visible && AUTO_HIDE) {
                // Schedule a hide().
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }

        }
    });

    // Set up the user interaction to manually show or hide the system UI.
    contentView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (TOGGLE_ON_CLICK) {
                mSystemUiHider.toggle();
            } else {
                mSystemUiHider.show();
            }
        }
    });

    // Upon interacting with UI controls, delay any scheduled hide()
    // operations to prevent the jarring behavior of controls going away
    // while interacting with the UI.
    prevButton.setOnTouchListener(mDelayHideTouchListener);
    nextButton.setOnTouchListener(mDelayHideTouchListener);

    try {
        summaryUrl = "http://www.instapaper.com/text?u=" + urlList.get(urlId);
    } catch (Exception e) {
        e.printStackTrace();
    }

    instapaperView.loadUrl(summaryUrl);
    prevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                summaryUrl = "http://www.instapaper.com/text?u=" + urlList.get(--urlId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            instapaperView.loadUrl(summaryUrl);
        }
    });
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                summaryUrl = "http://www.instapaper.com/text?u=" + urlList.get(++urlId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            instapaperView.loadUrl(summaryUrl);
        }
    });

}

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

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

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

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

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

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

    wv.getSettings().setJavaScriptEnabled(true);

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

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

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

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

            return false;
        }
    });

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

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

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

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

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

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

                dialog.dismiss();
            }

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

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

            return url.startsWith(endUrl);
        }

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

            return url.startsWith(startUrl);
        }

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

                dialog.dismiss();
            }
        }
    });

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

From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(Context context) {
    // in IDE's preview mode
    if (isInEditMode()) {
        // do not run the code from this method
        return;//w  ww.ja  va  2  s.  c om
    }

    if (context instanceof Activity) {
        mActivity = new WeakReference<Activity>((Activity) context);
    }

    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.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setUserAgentString(ApiClientHelper.getUserAgent((AppContext) x.app()) + "/isapp");
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        webSettings.setDisplayZoomControls(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(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);

    webSettings.setJavaScriptCanOpenWindowsAutomatically(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(final WebView view, final String url) {
            // if the hostname may not be accessed
            if (!isHostnameAllowed(url)) {
                // if a listener is available
                if (mListener != null) {
                    // inform the listener about the request
                    mListener.onExternalPageRequest(url);
                }

                // cancel the original request
                return true;
            }

            // if there is a user-specified handler available
            if (mCustomWebViewClient != null) {
                // if the user-specified handler asks to override the request
                if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) {
                    // cancel the original request
                    return true;
                }
            }

            // route the request through the custom URL loading method
            view.loadUrl(url);

            // cancel the original request
            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")
        @TargetApi(21)
        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, false);
        }

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (Build.VERSION.SDK_INT >= 21) {
                final boolean allowMultiple = fileChooserParams
                        .getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;

                openFileInput(null, filePathCallback, allowMultiple);

                return true;
            } else {
                return false;
            }
        }

        @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(final String url, final String userAgent, final String contentDisposition,
                final String mimeType, final long contentLength) {
            final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType);

            if (mListener != null) {
                mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength,
                        contentDisposition, userAgent);
            }
        }

    });
}

From source file:com.loadsensing.app.Chart.java

private void generaChart(WebView googleChartView, int checkedId, String SensorSelected) {
    SharedPreferences settings = getSharedPreferences("LoadSensingApp", Context.MODE_PRIVATE);
    String address = SERVER_HOST + "?session=" + settings.getString("session", "") + "&id=" + SensorSelected
            + "&TipusGrafic=" + checkedId;

    ArrayList<HashMap<String, String>> valorsURL = new ArrayList<HashMap<String, String>>();

    try {//  ww  w . j a  va2 s  .  c  o  m
        String jsonString = JsonClient.connectString(address);

        // Convertim la resposta string a un JSONArray
        JSONArray ValorsGrafica = new JSONArray(jsonString);

        // En esta llamada slo hay 1 objeto
        JSONObject Valors = new JSONObject();
        Valors = ValorsGrafica.getJSONObject(0);

        String grafica = Valors.getString("ValorsGrafica");

        // Sobre el string de ValorGrafica, volvemos a parsearlo
        JSONArray ValorGrafica = new JSONArray(grafica);
        for (int i = 0; i < ValorGrafica.length(); i++) {
            JSONObject Valor = new JSONObject();
            Valor = ValorGrafica.getJSONObject(i);

            HashMap<String, String> valorHashMap = new HashMap<String, String>();
            valorHashMap.put("date", Valor.getString("date"));
            valorHashMap.put("value", Valor.getString("value"));
            valorsURL.add(valorHashMap);
        }

    } catch (Exception e) {
        Log.d(DEB_TAG, "Error rebent xarxes");
    }

    // Montamos URL
    String mUrl = CHART_URL;

    // Etiquetas eje X, columna 0 y 1
    mUrl = mUrl + "chxl=0:";
    for (int i = 3; i < valorsURL.size(); i += 4) {
        mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date"));
    }
    mUrl = mUrl + "|Fecha";
    mUrl = mUrl + "|1:";
    for (int i = 1; i < valorsURL.size(); i += 4) {
        mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date"));
    }

    // Posicin etiquetas eje Y
    mUrl = mUrl + "&chxp=0,30,70,110|1,10,50,90";

    // Rango x,y

    // Coger valor mnimo y mximo
    float max = new Float(valorsURL.get(0).get("value"));
    float min = new Float(valorsURL.get(0).get("value"));
    for (int i = 1; i < valorsURL.size(); i++) {
        Float valueFloat = new Float(valorsURL.get(i).get("value"));
        max = Math.max(max, valueFloat);
        min = Math.min(min, valueFloat);
    }

    BigDecimal maxRounded = new BigDecimal(max);
    maxRounded = maxRounded.setScale(1, BigDecimal.ROUND_CEILING);
    BigDecimal minRounded = new BigDecimal(min);
    minRounded = minRounded.setScale(1, BigDecimal.ROUND_FLOOR);

    mUrl = mUrl + "&chxr=0,-5,110|1,-5,110|2," + minRounded + "," + maxRounded;

    // Ejes visibles
    mUrl = mUrl + "&chxt=x,x,y";

    // Tipo de grfico
    mUrl = mUrl + "&cht=lxy";

    // Medida del grfico
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth() - 170;
    int height = display.getHeight() - 390;
    mUrl = mUrl + "&chs=" + width + "x" + height;

    // Colores
    mUrl = mUrl + "&chco=3072F3";

    // Escala
    mUrl = mUrl + "&chds=0,9," + minRounded + "," + maxRounded;

    // Valores
    mUrl = mUrl + "&chd=t:0";
    for (int i = 1; i < valorsURL.size(); i++) {
        mUrl = mUrl + "," + i;
    }
    mUrl = mUrl + "|";
    mUrl = mUrl + valorsURL.get(0).get("value");
    for (int i = 1; i < valorsURL.size(); i++) {
        mUrl = mUrl + "," + valorsURL.get(i).get("value");
    }

    // Ttulo eyenda
    switch (checkedId) {
    case R.id.radio1:
        mUrl = mUrl + "&chdl=Sensor+strain+(V)&chdlp=b";
        break;
    case R.id.radio2:
        mUrl = mUrl + "&chdl=Excitation+power+(V)&chdlp=b";
        break;
    case R.id.radio3:
        mUrl = mUrl + "&chdl=Counter+(cnts)&chdlp=b";
        break;
    }

    // Estilo de lineas
    mUrl = mUrl + "&chls=2";

    // Mrgenes
    mUrl = mUrl + "&chma=0,5,5,25|5";

    // Marcador
    mUrl = mUrl + "&chm=r,FF0000,0,0,0";

    Log.d(DEB_TAG, "URL Chart " + mUrl);

    googleChartView.loadUrl(mUrl);
}

From source file:com.mimo.service.api.MimoOauth2Client.java

/**
 * Instantiate a webview and allows the user to login to the Api form within
 * the application/*w w w  . j a  v a  2  s . c  om*/
 * 
 * @param p_view
 *            : Calling view
 * 
 * @param p_activity
 *            : Calling Activity reference
 **/

@SuppressLint("SetJavaScriptEnabled")
public void login(View p_view, Activity p_activity) {

    final Activity m_activity;
    m_activity = p_activity;
    String m_url = this.m_api.getAuthUrl();
    WebView m_webview = new WebView(p_view.getContext());
    m_webview.getSettings().setJavaScriptEnabled(true);
    m_webview.setVisibility(View.VISIBLE);
    m_activity.setContentView(m_webview);

    m_webview.requestFocus(View.FOCUS_DOWN);
    /**
     * Open the softkeyboard of the device to input the text in form which
     * loads in webview.
     */
    m_webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View p_v, MotionEvent p_event) {
            switch (p_event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!p_v.hasFocus()) {
                    p_v.requestFocus();
                }
                break;
            }
            return false;
        }
    });

    /**
     * Show the progressbar in the title of the activity untill the page
     * loads the give url.
     */
    m_webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView p_view, int p_newProgress) {
            ((Activity) m_context).setProgress(p_newProgress * 100);
            ((Activity) m_context).setTitle(MimoAPIConstants.DIALOG_TEXT_LOADING);

            if (p_newProgress == 100)
                ((Activity) m_context).setTitle(m_context.getString(R.string.app_name));
        }
    });

    m_webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView p_view, String p_url, Bitmap p_favicon) {
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView p_view, HttpAuthHandler p_handler, String p_url,
                String p_realm) {
            p_handler.proceed(MimoAPIConstants.USERNAME, MimoAPIConstants.PASSWORD);
        }

        public void onPageFinished(WebView p_view, String p_url) {
            if (MimoAPIConstants.DEBUG) {
                Log.d(TAG, "Page Url = " + p_url);
            }
            if (p_url.contains("?code=")) {
                if (p_url.indexOf("code=") != -1) {
                    String[] m_urlSplit = p_url.split("=");

                    String m_tempString1 = m_urlSplit[1];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "TempString1 = " + m_tempString1);
                    }
                    String[] m_urlSplit1 = m_tempString1.split("&");

                    String m_code = m_urlSplit1[0];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "code = " + m_code);
                    }
                    MimoOauth2Client.this.m_code = m_code;
                    Thread m_thread = new Thread() {
                        public void run() {
                            String m_token = requesttoken(MimoOauth2Client.this.m_code);

                            Log.d(TAG, "Token = " + m_token);

                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);

                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);

                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                } else {
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "going in else");
                    }
                }
            } else if (p_url.contains(MimoAPIConstants.URL_KEY_TOKEN)) {
                if (p_url.indexOf(MimoAPIConstants.URL_KEY_TOKEN) != -1) {
                    String[] m_urlSplit = p_url.split("=");
                    final String m_token = m_urlSplit[1];

                    Thread m_thread = new Thread() {
                        public void run() {
                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);
                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);
                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                }
            }
        };
    });

    m_webview.loadUrl(m_url);
}

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 w w  w  . j a  v  a2 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.nttec.everychan.ui.gallery.GalleryActivity.java

private void setWebView(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        private boolean oomFlag = false;

        private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        private void prepareWebView(WebView webView) {
            webView.setBackgroundColor(Color.TRANSPARENT);
            webView.setInitialScale(100);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                CompatibilityImpl.setScrollbarFadingEnabled(webView, true);
            }//from  ww w  . ja va2 s.  c om

            WebSettings settings = webView.getSettings();
            settings.setBuiltInZoomControls(true);
            settings.setSupportZoom(true);
            settings.setAllowFileAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                CompatibilityImpl.setDefaultZoomFAR(settings);
                CompatibilityImpl.setLoadWithOverviewMode(settings, true);
            }
            settings.setUseWideViewPort(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                CompatibilityImpl.setBlockNetworkLoads(settings, true);
            }

            setScaleWebView(webView);
        }

        private void setScaleWebView(final WebView webView) {
            Runnable callSetScaleWebView = new Runnable() {
                @Override
                public void run() {
                    setPrivateScaleWebView(webView);
                }
            };

            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());
            if (resolution.equals(0, 0)) {
                // wait until the view is measured and its size is known
                AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView);
            } else {
                callSetScaleWebView.run();
            }
        }

        private void setPrivateScaleWebView(WebView webView) {
            Point imageSize = getImageSize(file);
            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());

            //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y);
            double scaleX = (double) resolution.x / (double) imageSize.x;
            double scaleY = (double) resolution.y / (double) imageSize.y;
            int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d);
            scale = Math.max(scale, 1);
            //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX;
                if (picdpi >= 240) {
                    CompatibilityImpl.setDefaultZoomFAR(webView.getSettings());
                } else if (picdpi <= 120) {
                    CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings());
                } else {
                    CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings());
                }
            }

            webView.setInitialScale(scale);
            webView.setPadding(0, 0, 0, 0);
        }

        private Point getImageSize(File file) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            return new Point(options.outWidth, options.outHeight);
        }

        private boolean useFallback(File file) {
            String path = file.getPath().toLowerCase(Locale.US);
            if (path.endsWith(".png"))
                return false;
            if (path.endsWith(".jpg"))
                return false;
            if (path.endsWith(".gif"))
                return false;
            if (path.endsWith(".jpeg"))
                return false;
            if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                return false;
            return true;
        }

        @Override
        public void run() {
            try {
                recycleTag(tag, false);
                WebView webView = new WebViewFixed(GalleryActivity.this);
                webView.setLayoutParams(MATCH_PARAMS);
                tag.layout.addView(webView);
                if (settings.fallbackWebView() || useFallback(file)) {
                    prepareWebView(webView);
                    webView.loadUrl(Uri.fromFile(file).toString());
                } else {
                    JSWebView.setImage(webView, file);
                }
                tag.thumbnailView.setVisibility(View.GONE);
                tag.loadingView.setVisibility(View.GONE);
                tag.layout.setVisibility(View.VISIBLE);
            } catch (OutOfMemoryError oom) {
                System.gc();
                Logger.e(TAG, oom);
                if (!oomFlag) {
                    oomFlag = true;
                    run();
                } else
                    showError(tag, getString(R.string.error_out_of_memory));
            }
        }

    });
}

From source file:org.golang.app.WViewActivity.java

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

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);//ww w.j a  v a 2 s  .  co m
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

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

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:nya.miku.wishmaster.ui.GalleryActivity.java

private void setWebView(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        private boolean oomFlag = false;

        private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        private void prepareWebView(WebView webView) {
            webView.setBackgroundColor(Color.TRANSPARENT);
            webView.setInitialScale(100);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                CompatibilityImpl.setScrollbarFadingEnabled(webView, true);
            }//from w w  w.  ja v a 2  s . co m

            WebSettings settings = webView.getSettings();
            settings.setBuiltInZoomControls(true);
            settings.setSupportZoom(true);
            settings.setAllowFileAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                CompatibilityImpl.setDefaultZoomFAR(settings);
                CompatibilityImpl.setLoadWithOverviewMode(settings, true);
            }
            settings.setUseWideViewPort(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                CompatibilityImpl.setBlockNetworkLoads(settings, true);
            }

            setScaleWebView(webView);
        }

        private void setScaleWebView(final WebView webView) {
            Runnable callSetScaleWebView = new Runnable() {
                @Override
                public void run() {
                    setPrivateScaleWebView(webView);
                }
            };

            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());
            if (resolution.equals(0, 0)) {
                // wait until the view is measured and its size is known
                AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView);
            } else {
                callSetScaleWebView.run();
            }
        }

        private void setPrivateScaleWebView(WebView webView) {
            Point imageSize = getImageSize(file);
            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());

            //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y);
            double scaleX = (double) resolution.x / (double) imageSize.x;
            double scaleY = (double) resolution.y / (double) imageSize.y;
            int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d);
            scale = Math.max(scale, 1);
            //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX;
                if (picdpi >= 240) {
                    CompatibilityImpl.setDefaultZoomFAR(webView.getSettings());
                } else if (picdpi <= 120) {
                    CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings());
                } else {
                    CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings());
                }
            }

            webView.setInitialScale(scale);
            webView.setPadding(0, 0, 0, 0);
        }

        private Point getImageSize(File file) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            return new Point(options.outWidth, options.outHeight);
        }

        private boolean useFallback(File file) {
            String path = file.getPath().toLowerCase(Locale.US);
            if (path.endsWith(".png"))
                return false;
            if (path.endsWith(".jpg"))
                return false;
            if (path.endsWith(".gif"))
                return false;
            if (path.endsWith(".jpeg"))
                return false;
            if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                return false;
            return true;
        }

        @Override
        public void run() {
            try {
                recycleTag(tag, false);
                WebView webView = new WebViewFixed(GalleryActivity.this);
                webView.setLayoutParams(MATCH_PARAMS);
                tag.layout.addView(webView);
                if (settings.fallbackWebView() || useFallback(file)) {
                    prepareWebView(webView);
                    webView.loadUrl(Uri.fromFile(file).toString());
                } else {
                    JSWebView.setImage(webView, file);
                }
                tag.thumbnailView.setVisibility(View.GONE);
                tag.loadingView.setVisibility(View.GONE);
                tag.layout.setVisibility(View.VISIBLE);
            } catch (OutOfMemoryError oom) {
                MainApplication.freeMemory();
                Logger.e(TAG, oom);
                if (!oomFlag) {
                    oomFlag = true;
                    run();
                } else
                    showError(tag, getString(R.string.error_out_of_memory));
            }
        }

    });
}

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

@Override
public void create() {
    try {//ww w .  ja  va2 s  .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) {
    }
}