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:Main.java

private static boolean setProxyPreICS(WebView webView, String host, final int port) {
    HttpHost proxyServer;/*from  w w  w.j av a 2  s.  com*/
    if (null == host) {
        proxyServer = null;
    } else {
        proxyServer = new HttpHost(host, port);
    }
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webView.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:com.dubsar_dictionary.Dubsar.FAQActivity.java

/**
 * Set Proxy for Android 3.2 and below./*from  w w w .j  a  v a2s  .  c  o m*/
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:org.ciasaboark.tacere.activity.AboutLicenseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_activity_license);
    // Show the Up button in the action bar.
    setupActionBar();/*from   w w w  .  j a  v  a 2 s. com*/

    WebView wv = (WebView) findViewById(R.id.webView1);

    String htmlData = "";
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("license.html")));

        String line;
        while ((line = br.readLine()) != null) {
            htmlData += line;
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }

    int colorInt = getResources().getColor(R.color.link_color);
    String hexColor = String.format("#%06X", (0xFFFFFF & colorInt));
    while (htmlData.contains("LINKCOLOR")) {
        htmlData = htmlData.replace("LINKCOLOR", hexColor);
    }

    wv.loadData(htmlData, "text/html", "UTF8");

    // All links should open in the default browser, not this WebView
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    wv.setBackgroundColor(0x00000000);
    wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

From source file:org.ciasaboark.tacere.activity.fragment.AboutLicenseFragment.java

private void initViews() {
    // Show the Up button in the action bar.
    //        setupActionBar();

    WebView wv = (WebView) rootView.findViewById(R.id.webView1);

    String htmlData = "";
    try {//from  www .j  a v  a 2  s . c om
        BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("license.html")));

        String line;
        while ((line = br.readLine()) != null) {
            htmlData += line;
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }

    int colorInt = getResources().getColor(R.color.link_color);
    String hexColor = String.format("#%06X", (0xFFFFFF & colorInt));
    while (htmlData.contains("LINKCOLOR")) {
        htmlData = htmlData.replace("LINKCOLOR", hexColor);
    }

    wv.loadData(htmlData, "text/html", "UTF8");

    // All links should open in the default browser, not this WebView
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    wv.setBackgroundColor(0x00000000);
    wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

From source file:net.kourlas.voipms_sms.activities.CreditsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.credits);/* ww  w .j a v  a2s .c  o  m*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation));
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    WebView browser = (WebView) findViewById(R.id.web_view);
    browser.loadUrl(getString(R.string.credits_url));
    browser.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }
    });
}

From source file:net.kourlas.voipms_sms.activities.HelpActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.help);/*from w w  w.  j a  v a  2  s .  c om*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation));
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    WebView browser = (WebView) findViewById(R.id.web_view);
    browser.loadUrl(getString(R.string.help_url));
    browser.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }
    });
}

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

private void loadAbout(final WebView webView) {
    final Resources resources = webView.getContext().getResources();

    final Map<String, String> substitutionMap = new ArrayMap<>();
    final String appName = webView.getContext().getResources().getString(R.string.app_name);
    final String learnMoreURL = SupportUtils.getManifestoURL();

    final String aboutContent = resources.getString(R.string.about_content, appName, learnMoreURL);
    substitutionMap.put("%about-content%", aboutContent);

    final String wordmark = HtmlLoader.loadPngAsDataURI(webView.getContext(), R.drawable.wordmark);
    substitutionMap.put("%wordmark%", wordmark);

    final String data = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.about, substitutionMap);
    // We use a file:/// base URL so that we have the right origin to load file:/// css and
    // image resources.
    webView.loadDataWithBaseURL("file:///android_res/raw/about.html", data, "text/html", "UTF-8", null);
}

From source file:com.juick.android.Utils.java

public static void setupWebView(final WebView wv, String content) {
    try {/*from  w w  w. j av a  2 s. com*/
        if (skipWeb)
            return;
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(wv.getContext());
        File file = new File(wv.getContext().getCacheDir(), "temp.html");
        String PREFIX = "#prefs.checked.";
        while (true) {
            int ix = content.indexOf(PREFIX);
            if (ix == -1)
                break;
            int ix2 = content.indexOf("#", ix + 1);
            if (ix2 == -1)
                break;
            String key = content.substring(ix + PREFIX.length(), ix2);
            boolean def = false;
            if (key.endsWith("!")) {
                def = true;
                key = key.substring(0, key.length() - 1);
            }
            boolean checked = sp.getBoolean(key, def);
            content = content.substring(0, ix) + (checked ? "checked" : "") + content.substring(ix2 + 1);
        }
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
        wv.getSettings().setJavaScriptEnabled(true);
        //            wv.getSettings().setBlockNetworkImage(false);
        //            wv.getSettings().setBlockNetworkLoads(false);
        wv.getSettings().setLoadsImagesAutomatically(true);
        Uri uri = Uri.fromFile(file);
        wv.addJavascriptInterface(new Object() {
            public void onFormData(String str) {
                wv.setTag(str);
            }
        }, "EXT");
        wv.loadUrl(uri.toString());
    } catch (IOException e) {
        //
    }

}

From source file:justforcommunity.radiocom.activities.ContentDetail.java

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

    setContentView(R.layout.activity_contentdetail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from w  w w.j a v  a2s  .  c o m
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    prefs = this.getSharedPreferences(GlobalValues.prefName, Context.MODE_PRIVATE);
    edit = prefs.edit();

    detail_web = (WebView) findViewById(R.id.detail_web);

    content = getIntent().getStringExtra(GlobalValues.EXTRA_CONTENT);

    detail_web.setBackgroundColor(Color.WHITE);

    title = getIntent().getStringExtra(GlobalValues.EXTRA_TITLE);

    getSupportActionBar().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    try {
        content = content.replaceAll("style=\".+?\"", "");
    } catch (Exception e) {

    }

    String fontscript = "";
    String script = "<style type='text/css' >p{width:100%;}img{width:100%;height:auto;-webkit-transform: translate3d(0px,0px,0px);}a,h1,h2,h3,h4,h5,h6{color:"
            + GlobalValues.colorHTML
            + ";}div,p,span,a {max-width: 100%;}iframe{width:100%;height:auto;}</style>";

    detail_web.loadDataWithBaseURL(
            GlobalValues.baseURLWEB, "<html><head>" + fontscript + script
                    + "</head><body style=\"font-family:HelveticaNeue-Light; \">" + content + "</body></html>",
            "text/html", "utf-8", "");
    detail_web.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if ((url != null && url.startsWith("http://")) || (url != null && url.startsWith("https://"))) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }

        }

        public void onPageFinished(WebView view, String url) {
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        }
    });
    detail_web.getSettings().setDomStorageEnabled(true);
    detail_web.getSettings().setJavaScriptEnabled(true);

    App appliaction = (App) getApplication();
    Tracker mTracker = appliaction.getDefaultTracker();
    mTracker.setScreenName(getString(R.string.content_activity));
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

}

From source file:at.maui.cheapcast.fragment.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///  ww w .j  a v a2 s  .  com
 */
@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);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = mFlattrProjectUrl;
    String flattrUrl = this.mFlattrUrl;

    // 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 + flattrUrl);

    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='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' 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);
}