Example usage for android.webkit WebView getContext

List of usage examples for android.webkit WebView getContext

Introduction

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

Prototype

@ViewDebug.CapturedViewProperty
public final Context getContext() 

Source Link

Document

Returns the context the view is running in, through which it can access the current theme, resources, etc.

Usage

From source file:com.google.android.apps.paco.ExploreDataActivity.java

private void setWebChromeClientThatHandlesAlertsAsDialogs() {
    webView.setWebChromeClient(new WebChromeClient() {
        @Override/*from   w ww .  j  a  v  a 2  s  .c o  m*/
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true)
                    .setPositiveButton(R.string.ok, new Dialog.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }

                    }).create().show();
            result.confirm();
            return true;
        }

        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            if (url.contains("file:///android_asset/map.html")) {
                if (showDialog == false) {
                    result.confirm();
                    return true;
                } else {
                    new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true)
                            .setPositiveButton(R.string.ok, new Dialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    showDialog = false;
                                    dialog.dismiss();
                                    result.confirm();
                                }
                            }).setNegativeButton(R.string.cancel_button, new Dialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    result.cancel();
                                }
                            }).create().show();
                    return true;
                }
            }
            return super.onJsConfirm(view, url, message, result);
        }
    });
}

From source file:org.mozilla.focus.webkit.ErrorPage.java

public static void loadErrorPage(final WebView webView, final String desiredURL, final int errorCode) {
    final Pair<Integer, Integer> errorResourceIDs = errorDescriptionMap.get(errorCode);

    if (errorResourceIDs == null) {
        throw new IllegalArgumentException(
                "Cannot load error description for unsupported errorcode=" + errorCode);
    }//from  www  . j  a va2 s.c om

    // This is quite hacky: ideally we'd just load the css file directly using a '<link rel="stylesheet"'.
    // However webkit thinks it's still loading the original page, which can be an https:// page.
    // If mixed content blocking is enabled (which is probably what we want in Focus), then webkit
    // will block file:///android_res/ links from being loaded - which blocks our css from being loaded.
    // We could hack around that by enabling mixed content when loading an error page (and reenabling it
    // once that's loaded), but doing that correctly and reliably isn't particularly simple. Loading
    // the css data and stuffing it into our html is much simpler, especially since we're already doing
    // string substitutions.
    // As an added bonus: file:/// URIs are broken if the app-ID != app package, see:
    // https://code.google.com/p/android/issues/detail?id=211768 (this breaks loading css via file:///
    // references when running debug builds, and probably klar too) - which means this wouldn't
    // be possible even if we hacked around the mixed content issues.
    final String cssString = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage_style, null);

    final Map<String, String> substitutionMap = new ArrayMap<>();

    final Resources resources = webView.getContext().getResources();

    substitutionMap.put("%page-title%", resources.getString(R.string.errorpage_title));
    substitutionMap.put("%button%", resources.getString(R.string.errorpage_refresh));

    substitutionMap.put("%messageShort%", resources.getString(errorResourceIDs.first));
    substitutionMap.put("%messageLong%", resources.getString(errorResourceIDs.second, desiredURL));

    substitutionMap.put("%css%", cssString);

    final String errorPage = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage,
            substitutionMap);

    // We could load the raw html file directly into the webview using a file:///android_res/
    // URI - however we'd then need to do some JS hacking to do our String substitutions. Moreover
    // we'd have to deal with the mixed-content issues detailed above in that case.
    webView.loadDataWithBaseURL(desiredURL, errorPage, "text/html", "UTF8", desiredURL);
}

From source file:org.mozilla.focus.webview.ErrorPage.java

public static void loadErrorPage(final WebView webView, final String desiredURL, final int errorCode) {
    final Pair<Integer, Integer> errorResourceIDs = errorDescriptionMap.get(errorCode);

    if (errorResourceIDs == null) {
        throw new IllegalArgumentException(
                "Cannot load error description for unsupported errorcode=" + errorCode);
    }//from   w w w.jav a2  s. c  om

    // This is quite hacky: ideally we'd just load the css file directly using a '<link rel="stylesheet"'.
    // However WebView thinks it's still loading the original page, which can be an https:// page.
    // If mixed content blocking is enabled (which is probably what we want in Focus), then webkit
    // will block file:///android_res/ links from being loaded - which blocks our css from being loaded.
    // We could hack around that by enabling mixed content when loading an error page (and reenabling it
    // once that's loaded), but doing that correctly and reliably isn't particularly simple. Loading
    // the css data and stuffing it into our html is much simpler, especially since we're already doing
    // string substitutions.
    // As an added bonus: file:/// URIs are broken if the app-ID != app package, see:
    // https://code.google.com/p/android/issues/detail?id=211768 (this breaks loading css via file:///
    // references when running debug builds, and probably klar too) - which means this wouldn't
    // be possible even if we hacked around the mixed content issues.
    final String cssString = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage_style, null);

    final Map<String, String> substitutionMap = new ArrayMap<>();

    final Resources resources = webView.getContext().getResources();

    substitutionMap.put("%page-title%", resources.getString(R.string.errorpage_title));
    substitutionMap.put("%button%", resources.getString(R.string.errorpage_refresh));

    substitutionMap.put("%messageShort%", resources.getString(errorResourceIDs.first));
    substitutionMap.put("%messageLong%", resources.getString(errorResourceIDs.second, desiredURL));

    substitutionMap.put("%css%", cssString);

    final String errorPage = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage,
            substitutionMap);

    // We could load the raw html file directly into the webview using a file:///android_res/
    // URI - however we'd then need to do some JS hacking to do our String substitutions. Moreover
    // we'd have to deal with the mixed-content issues detailed above in that case.
    webView.loadDataWithBaseURL(desiredURL, errorPage, "text/html", "UTF8", desiredURL);
}

From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button/// www  .  ja v  a  2  s .c  o m
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                WebView.HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    TextView mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:org.sufficientlysecure.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///from   w w  w  .j  av a  2  s . c om
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private void setAttributes() {
    if (mAttributes == null)
        return;// w w  w . j  a va 2s  .com

    mAttributes.removeAllViews();

    int[] attrs = new int[] { android.R.attr.textColorPrimary };
    TypedArray ta = getContext().obtainStyledAttributes(attrs);
    String textColor = Integer.toHexString(ta.getColor(0, Color.BLACK)).substring(2);
    ta.recycle();

    final WebView webView = new WebView(getContext());
    webView.setVerticalScrollBarEnabled(false);
    String data = "<!DOCTYPE html><html><head><meta charset='utf-8'><style>body{word-wrap:break-word;color:#"
            + textColor
            + ";font-family:Roboto Light,sans-serif;font-weight:300;line-height:1.15em}.flat-table{table-layout:fixed;margin-bottom:20px;width:100%;border-collapse:collapse;border:none;box-shadow:inset 1px -1px #ccc,inset -1px 1px #ccc}.flat-table td{box-shadow:inset -1px -1px #ccc,inset -1px -1px #ccc;padding:.5em}.flat-table tr{-webkit-transition:background .3s,box-shadow .3s;-moz-transition:background .3s,box-shadow .3s;transition:background .3s,box-shadow .3s}</style></head><body><table class='flat-table'><tbody>";

    FragmentActivity activity = getActivity();
    if (null == activity)
        return;

    ((MainActivity) activity).setSubtitle(String.format(getString(R.string.features_count_attributes),
            mItemPosition + 1, mFeatureIDs.size()));
    checkNearbyItems();

    try {
        data = parseAttributes(data);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

    data += "</tbody></table></body></html>";
    webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
    mAttributes.addView(webView);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.setBackgroundColor(Color.TRANSPARENT);
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    IGISApplication app = (GISApplication) getActivity().getApplication();
    final Map<String, Integer> mAttaches = new HashMap<>();
    PhotoGallery.getAttaches(app, mLayer, mItemId, mAttaches, false);

    if (mAttaches.size() > 0) {
        final PhotoPicker gallery = new PhotoPicker(getActivity(), true);
        int px = ControlHelper.dpToPx(16, getResources());
        gallery.setDefaultPreview(true);
        gallery.setPadding(px, 0, px, 0);
        gallery.post(new Runnable() {
            @Override
            public void run() {
                gallery.restoreImages(new ArrayList<>(mAttaches.keySet()));
            }
        });

        mAttributes.addView(gallery);
    }
}

From source file:org.rapidandroid.activity.chart.ChartBroker.java

protected ChartBroker(Activity activity, WebView appView, Date startDate, Date endDate) {
    mParentActivity = activity;/*from w  w  w.  j ava  2  s.com*/
    mAppView = appView;
    rawDB = new SmsDbHelper(appView.getContext());
    // mVariableStrings = new String[] { "Trends by day",
    // "Receipt time of day" };
    mStartDate = startDate;
    mEndDate = endDate;
}

From source file:felixwiemuth.lincal.ui.HtmlDialogFragment.java

private boolean loadUrl(WebView webView, Uri uri) {
    if (uri.getScheme().equals("file")) {
        webView.loadUrl(uri.toString());
    } else if (uri.getScheme().equals("action")) {
        List<String> segments = uri.getPathSegments();
        if (segments.isEmpty()) {
            throw new RuntimeException("Error in WebView: No action name provided.");
        } else {// w  w  w  .j  a va 2  s  .c  om
            handleAction(segments.get(0), segments.subList(1, segments.size()));
        }
    } else {
        // If the URI is not pointing to a local file, open with an ACTION_VIEW Intent
        webView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }
    return true; // in both cases we handle the link manually
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
public void onDropViewInstance(WebView webView) {
    super.onDropViewInstance(webView);
    ((ThemedReactContext) webView.getContext()).removeLifecycleEventListener((ReactWebView) webView);
    ((ReactWebView) webView).cleanupCallbacksAndDestroy();
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Print a {@link WebView}'s contents, also allows to create a PDF
 *
 * @param webview WebView/*from   ww w.jav a  2 s .  co m*/
 * @param jobName Name of the job (affects PDF name too)
 * @return {{@link PrintJob}} or null
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@SuppressWarnings("deprecation")
public PrintJob print(WebView webview, String jobName) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        PrintDocumentAdapter printAdapter;
        PrintManager printManager = (PrintManager) webview.getContext().getSystemService(Context.PRINT_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            printAdapter = webview.createPrintDocumentAdapter(jobName);
        } else {
            printAdapter = webview.createPrintDocumentAdapter();
        }
        if (printManager != null) {
            return printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
        }
    } else {
        Log.e(getClass().getName(), "ERROR: Method called on too low Android API version");
    }
    return null;
}