Example usage for android.webkit WebView WebView

List of usage examples for android.webkit WebView WebView

Introduction

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

Prototype

public WebView(Context context) 

Source Link

Document

Constructs a new WebView with an Activity Context object.

Usage

From source file:com.chuger.bithdayapp.view.auth.AuthDialog.java

private void setUpWebView(final int margin) {
    final LinearLayout webViewContainer = new LinearLayout(getContext());
    mWebView = new WebView(getContext());
    mWebView.setVerticalScrollBarEnabled(false);
    mWebView.setHorizontalScrollBarEnabled(false);
    mWebView.setWebViewClient(new AuthDialog.FbWebViewClient());
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl(mUrl);/*from  w  w w.j  a  v  a 2s . c  o  m*/
    mWebView.setLayoutParams(FILL);
    mWebView.setVisibility(View.INVISIBLE);

    webViewContainer.setPadding(margin, margin, margin, margin);
    webViewContainer.addView(mWebView);
    mContent.addView(webViewContainer);
}

From source file:no.barentswatch.fiskinfo.MapActivity.java

@SuppressLint({ "SetJavaScriptEnabled" })
private void configureWebParametersAndLoadDefaultMapApplication() {
    browser = new WebView(getContext());
    browser = (WebView) findViewById(R.id.browserWebView);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setDomStorageEnabled(true);
    browser.getSettings().setGeolocationEnabled(true);
    browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    browser.addJavascriptInterface(new JavaScriptInterface(getContext()), "Android");
    browser.setWebViewClient(new barentswatchFiskInfoWebClient());
    browser.setWebChromeClient(new WebChromeClient() {

        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            Log.d("geolocation permission", "permission >>>" + origin);
            callback.invoke(origin, true, false);
        }//  ww  w. jav a 2 s .c  o  m

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.i("my log", "Alert box popped");
            return super.onJsAlert(view, url, message, result);
        }
    });
    updateMapTools();
    browser.loadUrl("file:///android_asset/mapApplication.html");

}

From source file:com.nineducks.hereader.ui.NewsItemsFragment.java

private void initUI() {
    Log.d("hereader", "Creating UI");
    webViewContainer = (FrameLayout) getActivity().findViewById(R.id.webview_container);
    mDualPane = webViewContainer != null && webViewContainer.getVisibility() == View.VISIBLE;
    actionBar = (ActionBar) getActivity().findViewById(R.id.action_bar);
    actionBar.setHomeIcon(R.drawable.hackful_icon);
    actionBar.addAction(new LoadFrontpageItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new LoadNewItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new LoadAskItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new AboutAction(HackfulReaderActivity.getContext(), this));
    if (mDualPane || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        actionBar.setTitle(R.string.app_name);
    }/*from  w w w.ja v  a  2s.c  o m*/
    if (mDualPane) {
        if (webView == null) {
            Log.d("hereader", "WebView is null, creating new instance");
            final ActionBar actionB = actionBar;
            webView = new WebView(getActivity());
            webView.setId(R.id.webview_id);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setSupportZoom(true);
            //webView.getSettings().setBuiltInZoomControls(false);
            webView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress == 100) {
                        actionB.setProgressBarVisibility(View.GONE);
                    }
                }

            });
        }
        webViewContainer.addView(webView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    }
    Log.d("hereader", "UI created");
}

From source file:microsoft.aspnet.signalr.client.test.integration.android.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        startActivity(new Intent(this, SignalRPreferenceActivity.class));
        return true;

    case R.id.menu_run_tests:
        if (ApplicationContext.getServerUrl().trim().equals("")) {
            startActivity(new Intent(this, SignalRPreferenceActivity.class));
        } else {/*from   w  w  w .  j  ava 2 s  . co m*/
            runTests();
        }
        return true;

    case R.id.menu_check_all:
        changeCheckAllTests(true);
        return true;

    case R.id.menu_uncheck_all:
        changeCheckAllTests(false);
        return true;

    case R.id.menu_reset:
        refreshTestGroupsAndLog();
        return true;

    case R.id.menu_view_log:
        AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this);
        logDialogBuilder.setTitle("Log");

        final WebView webView = new WebView(this);

        String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />");
        String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>";
        webView.loadData(logHtml, "text/html", "utf-8");

        logDialogBuilder.setPositiveButton("Copy", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setText(mLog.toString());
            }
        });

        final String postContent = mLog.toString();

        logDialogBuilder.setNeutralButton("Post data", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            String url = ApplicationContext.getLogPostURL();
                            if (url != null && url.trim() != "") {
                                url = url + "?platform=android";
                                HttpPost post = new HttpPost();
                                post.setEntity(new StringEntity(postContent, "utf-8"));

                                post.setURI(new URI(url));

                                new DefaultHttpClient().execute(post);
                            }
                        } catch (Exception e) {
                            // Wasn't able to post the data. Do nothing
                        }

                        return null;
                    }
                }.execute();
            }
        });

        logDialogBuilder.setView(webView);

        logDialogBuilder.create().show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

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

@SuppressLint("SetJavaScriptEnabled")
private static void callInternalBrowser(AdWebView webView, Uri uri) {
    String urlParam = uri.getQueryParameter("url");

    if ((webView.getContext() == null) || (urlParam == null) || (!urlParam.startsWith("http"))) {
        return;/*from   w ww.java2 s  .  com*/
    }

    String url = Uri.decode(urlParam);
    Class<?> activity_clz = AdActivity.getActivityClass();

    Intent intent = new Intent(webView.getContext(), activity_clz);
    intent.putExtra(AdActivity.INTENT_KEY_ACTIVITY_TYPE, AdActivity.ACTIVITY_TYPE_BROWSER);

    WebView browserWebView = new WebView(webView.getContext());
    WebviewUtil.setWebViewSettings(browserWebView);
    BrowserAdActivity.BROWSER_QUEUE.add(browserWebView);
    browserWebView.loadUrl(url);

    if (webView.adView.getBrowserStyle() != null) {
        String i = "" + browserWebView.hashCode();
        intent.putExtra("bridgeid", i);
        AdView.BrowserStyle.bridge
                .add(new Pair<String, AdView.BrowserStyle>(i, webView.adView.getBrowserStyle()));
    }

    try {
        webView.getContext().startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(webView.getContext(), R.string.action_cant_be_completed, Toast.LENGTH_SHORT).show();
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.adactivity_missing, activity_clz.getName()));
        BrowserAdActivity.BROWSER_QUEUE.remove();
    }
}

From source file:io.github.hidroh.materialistic.SubmitActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        onBackPressed();//from  ww  w  . j  av  a  2 s  .c om
        return true;
    }
    if (item.getItemId() == R.id.menu_send) {
        if (!validate()) {
            return true;
        }
        final boolean isUrl = isUrl(mContentEditText.getText().toString());
        mAlertDialogBuilder.init(SubmitActivity.this)
                .setMessage(isUrl ? R.string.confirm_submit_url : R.string.confirm_submit_question)
                .setPositiveButton(android.R.string.ok, (dialog, which) -> submit(isUrl))
                .setNegativeButton(android.R.string.cancel, null).create().show();
        return true;
    }
    if (item.getItemId() == R.id.menu_guidelines) {
        WebView webView = new WebView(this);
        webView.loadUrl(HN_GUIDELINES_URL);
        mAlertDialogBuilder.init(this).setView(webView).setPositiveButton(android.R.string.ok, null).create()
                .show();
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.azure.webapi.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * //  w ww  .ja v a 2 s.c  o  m
 * @param provider
 *            The provider used for the 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
 */
protected void showLoginUI(MobileServiceAuthenticationProvider provider, 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.setTitle("Connecting to a service");
    builder.setCancelable(true);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

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

    // Set cancel button's action
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

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

    wv.getSettings().setJavaScriptEnabled(true);

    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:bolts.WebViewAppLinkResolver.java

@Override
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) {
    final Capture<String> content = new Capture<String>();
    final Capture<String> contentType = new Capture<String>();
    return Task.callInBackground(new Callable<Void>() {
        @Override/*  ww w . j av a 2s .c  om*/
        public Void call() throws Exception {
            URL currentURL = new URL(url.toString());
            URLConnection connection = null;
            while (currentURL != null) {
                // Fetch the content at the given URL.
                connection = currentURL.openConnection();
                if (connection instanceof HttpURLConnection) {
                    // Unfortunately, this doesn't actually follow redirects if they go from http->https,
                    // so we have to do that manually.
                    ((HttpURLConnection) connection).setInstanceFollowRedirects(true);
                }
                connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX);
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) {
                        currentURL = new URL(httpConnection.getHeaderField("Location"));
                        httpConnection.disconnect();
                    } else {
                        currentURL = null;
                    }
                } else {
                    currentURL = null;
                }
            }

            try {
                content.set(readFromConnection(connection));
                contentType.set(connection.getContentType());
            } finally {
                if (connection instanceof HttpURLConnection) {
                    ((HttpURLConnection) connection).disconnect();
                }
            }
            return null;
        }
    }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() {
        @Override
        public Task<JSONArray> then(Task<Void> task) throws Exception {
            // Load the content in a WebView and use JavaScript to extract the meta tags.
            final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>();
            final WebView webView = new WebView(context);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setNetworkAvailable(false);
            webView.setWebViewClient(new WebViewClient() {
                private boolean loaded = false;

                private void runJavaScript(WebView view) {
                    if (!loaded) {
                        // After the first resource has been loaded (which will be the pre-populated data)
                        // run the JavaScript meta tag extraction script
                        loaded = true;
                        view.loadUrl(TAG_EXTRACTION_JAVASCRIPT);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    runJavaScript(view);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);
                    runJavaScript(view);
                }
            });
            // Inject an object that will receive the JSON for the extracted JavaScript tags
            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void setValue(String value) {
                    try {
                        tcs.trySetResult(new JSONArray(value));
                    } catch (JSONException e) {
                        tcs.trySetError(e);
                    }
                }
            }, "boltsWebViewAppLinkResolverResult");
            String inferredContentType = null;
            if (contentType.get() != null) {
                inferredContentType = contentType.get().split(";")[0];
            }
            webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null);
            return tcs.getTask();
        }
    }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() {
        @Override
        public AppLink then(Task<JSONArray> task) throws Exception {
            Map<String, Object> alData = parseAlData(task.getResult());
            AppLink appLink = makeAppLinkFromAlData(alData, url);
            return appLink;
        }
    });
}

From source file:eu.trentorise.smartcampus.launcher.AppFragment.java

private void showDisclaimer() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    WebView wv = new WebView(getActivity());
    wv.loadData(getString(R.string.disclaimer), "text/html; charset=UTF-8", "utf-8");

    builder//.setTitle(android.R.string.dialog_alert_title)
            .setView(wv)/*from w  w  w  .  j a  v a 2  s  . c o m*/
            //            .setMessage(R.string.welcome_msg)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface arg0) {
                    arg0.dismiss();
                    getActivity().finish();
                }
            }).setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    getActivity().finish();
                }
            });
    builder.create().show();
}

From source file:com.googlecode.android_scripting.interpreter.html.HtmlActivityTask.java

@Override
public void onCreate() {
    mView = new WebView(getActivity());
    mView.setId(1);/*ww  w.  j av  a  2 s .c  o m*/
    mView.getSettings().setJavaScriptEnabled(true);
    mView.addJavascriptInterface(mWrapper, "_rpc_wrapper");
    mView.addJavascriptInterface(new Object() {

        @SuppressWarnings("unused")
        public void register(String event, int id) {
            mObserver.register(event, id);
        }
    }, "_callback_wrapper");

    getActivity().setContentView(mView);
    mView.setOnCreateContextMenuListener(getActivity());
    mChromeClient = new ChromeClient(getActivity());
    mWebViewClient = new MyWebViewClient();
    mView.setWebChromeClient(mChromeClient);
    mView.setWebViewClient(mWebViewClient);
    mView.loadUrl("javascript:" + mJsonSource);
    mView.loadUrl("javascript:" + mAndroidJsSource);
    mView.loadUrl("javascript:" + mAPIWrapperSource);
    load();
}