List of usage examples for android.webkit WebView getContext
@ViewDebug.CapturedViewProperty public final Context getContext()
From source file:eu.vranckaert.worktime.utils.donations.DonationsFragment.java
/** * Build view for Flattr. see Flattr API for more information: * http://developers.flattr.net/button///from w w w .j a va2 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) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString))); 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) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); 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 = DonationsUtils.getResourceString(getActivity(), "donations__flattr_project_url"); String flattrUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_url"); // 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 mFlattrUrl = (TextView) getActivity().findViewById(R.id.donations__flattr_url); mFlattrUrl.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"); // 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.pdi.hybridge.HybridgeWebChromeClient.java
@Override public final boolean onJsPrompt(WebView view, String url, String msg, String defValue, JsPromptResult result) { final String action = msg; JSONObject json = null;// w w w. j a va2 s . c o m Log.v(mTag, "Hybridge action: " + action); try { json = new JSONObject(defValue); Log.v(mTag, "JSON parsed (Action " + action + ") : " + json.toString()); executeJSONTask(action, json, result, HybridgeBroadcaster.getInstance(view), (Activity) view.getContext()); } catch (final JSONException e) { result.cancel(); Log.e(mTag, e.getMessage()); } return true; }
From source file:net.basov.ticketinfo.UI.java
public void displayWelcomeByNFC(WebView wv) { Context c = wv.getContext(); NfcAdapter adapter = NfcAdapter.getDefaultAdapter(c); if (adapter == null || !adapter.isEnabled()) { setWelcome("w_msg", "<font color=\"darkred\">" + c.getString(R.string.welcome_without_nfc) + "<font>"); } else {// ww w. jav a 2s . c o m setWelcome("w_msg", "<font color=\"darkgreen\">" + c.getString(R.string.welcome_with_nfc) + "<font>"); } displayWelcomeScreen(wv); }
From source file:com.google.android.apps.paco.FeedbackActivity.java
private void setWebChromeClientThatHandlesAlertsAsDialogs() { webView.setWebChromeClient(new WebChromeClient() { @Override// w w w .j av a 2 s.com 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); } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.d(PacoConstants.TAG, message + " -- From line " + lineNumber + " of " + sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.d(PacoConstants.TAG, "*" + consoleMessage.message() + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId()); return true; } }); }
From source file:info.guardianproject.netcipher.web.WebkitProxy.java
/** * Set Proxy for Android 3.2 and below./*w w w . ja va2s .c o m*/ */ @SuppressWarnings("all") private static boolean setProxyUpToHC(WebView webview, String host, int port) { Log.d(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(TAG, "failed to get class for android.webkit.Network"); return false; } Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class); if (getInstanceMethod == null) { Log.e(TAG, "failed to get getInstance method"); } network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() }); } catch (Exception ex) { Log.e(TAG, "error getting network: " + ex); return false; } if (network == null) { Log.e(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(TAG, "error getting field value"); return false; } if (requestQueue == null) { Log.e(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(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(TAG, "error setting proxy host"); } finally { proxyHostField.setAccessible(temp); } Log.d(TAG, "Setting proxy with <= 3.2 API successful!"); return true; }
From source file:net.basov.ticketinfo.UI.java
public void displayHelpScreen(String title, final WebView wv) { setHelp("h_header", title); setHelp("h_storage", FileIO.getFilesDir(wv.getContext()).getAbsolutePath()); wv.setWebViewClient(new MyWebViewClient() { @Override//from w ww . j a va 2 s . co m public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + help_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + help_json.toString() + "')"); } wv.clearCache(true); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.help_ui_file)); }
From source file:com.chatwingsdk.fragments.CommunicationMessagesFragment.java
private void setupWebView() { mWebview.setWebViewClient(new WebViewClient() { @Override//from w w w. j ava 2 s . c om public boolean shouldOverrideUrlLoading(WebView view, String url) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } catch (Exception e) { return false; } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //TODO should be when page start rendering chatbox LogUtils.v("Loading page DONE"); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); LogUtils.v("Loading page Oh no! " + description); } }); mWebview.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); LogUtils.v("Loading page " + newProgress + ":" + mWebview); } }); WebSettings webSettings = mWebview.getSettings(); webSettings.setAppCacheEnabled(false); webSettings.setJavaScriptEnabled(true); mWebview.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME); }
From source file:net.basov.ticketinfo.UI.java
public void displayWelcomeScreen(final WebView wv) { SharedPreferences defSharedPref = PreferenceManager.getDefaultSharedPreferences(wv.getContext()); setWelcome("s_lang", defSharedPref.getString(wv.getContext().getString(R.string.pk_app_lang), wv.getContext().getString(R.string.pref_lang_def))); if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_transliterate_flag), false)) { setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else {/*w w w . ja va2 s . c o m*/ setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\">"); } if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_send_platform_info), true)) { setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else { setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\">"); } if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_use_view_directory), false)) { setWelcome("s_use_view_directory", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else { setWelcome("s_use_view_directory", "<input type=\"checkbox\" disabled=\"disabled\">"); } wv.setWebViewClient(new MyWebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + welcome_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + welcome_json.toString() + "')", null); } wv.clearCache(true); wv.clearHistory(); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.welcome_ui_file)); }
From source file:com.example.prasadnr.traquad.TraQuad.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tra_quad); ConnectivityManager connManager = (ConnectivityManager) getSystemService(TraQuad.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); Builder alert = new AlertDialog.Builder(TraQuad.this); WifiManager managerWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); Method[] wmMethods = managerWifi.getClass().getDeclaredMethods(); for (Method method : wmMethods) { if (method.getName().equals("isWifiApEnabled")) { try { isWifiAPenabled = (boolean) method.invoke(managerWifi); } catch (IllegalArgumentException e) { e.printStackTrace();/*www. j a va 2s .co m*/ } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } final ProgressDialog pDialog; MediaController mediaController = new MediaController(this); pDialog = new ProgressDialog(TraQuad.this); pDialog.setTitle("TraQuad app (Connecting...)"); pDialog.setMessage("Buffering...Please wait..."); pDialog.setCancelable(true); if (!isWifiAPenabled) { alert.setTitle("WiFi Hotspot Settings"); alert.setMessage("Can you please connect WiFi-hotspot?"); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { irritation = true; startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); pDialog.show(); } }); alert.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Dismiss AlertDialog pDialog.show(); Toast.makeText(getApplicationContext(), "Please connect your WiFi!", Toast.LENGTH_LONG).show(); } }); alert.setCancelable(false); AlertDialog alertDialog = alert.create(); alertDialog.show(); } WebView webView = (WebView) findViewById(R.id.webView); if (irritation == true | isWifiAPenabled) { pDialog.show(); } mediaController.setAnchorView(webView); mediaController.setVisibility(View.GONE); extra = getIntent().getStringExtra("VideosId"); webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setPluginState(WebSettings.PluginState.ON); final GlobalClass globalVariable = (GlobalClass) getApplicationContext(); final String IPaddressNew = globalVariable.getIP(); final String httpString = "http://"; final String commandPort = String.valueOf(1500); final String streamPort = String.valueOf(8080); final String IPaddressStream = httpString + IPaddressNew + ":" + streamPort; final String IPaddressCommand = httpString + IPaddressNew + ":" + commandPort; TextView sendCharacter = (TextView) findViewById(R.id.sendCharacter); try { webView.loadUrl(IPaddressStream); } catch (Exception e) { Toast.makeText(getApplicationContext(), IPaddressNew + ":Error!", Toast.LENGTH_LONG).show(); } webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { pDialog.dismiss(); } }); final Button switchact = (Button) findViewById(R.id.btn2); switchact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent act1 = new Intent(view.getContext(), Joypad.class); startActivity(act1); } }); final Button hometraquad = (Button) findViewById(R.id.button5); hometraquad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent acthometraquad = new Intent(TraQuad.this, MainActivity.class); startActivity(acthometraquad); } }); }
From source file:net.basov.ticketinfo.UI.java
public void displayTicketInfo(NFCaDump d, Ticket t, WebView wv) { Context c = wv.getContext(); if (t.getTicketState() == Ticket.TS_UNKNOWN) t.detectTicketState();/*from ww w .j a va2s . c o m*/ this.setTicketHeader("h_state", t.getTicketStateAsHTML(c)); this.setTicketHeader("h_number", t.getTicketNumberAsString()); if (t.isDebugTimeSet()) { String DDDrem; if (d.getDDDRem() != null) { DDDrem = "<pre style=\"white-space: pre-wrap\">" + d.getDDDRem() + "</pre>"; } else { DDDrem = ""; } this.setTicket("t_debug", "<font color=\"Violet\">Debug time is: " + Ticket.DTF.format(t.getTimeToCompare().getTime()) + "</font>" + DDDrem); } this.setTicket("t_desc", Decode.descCardType(c, t.getTicketType(), t.getTicketTypeVersion())); if (t.getValidDays() != 0) { this.setTicket("t_valid_days", t.getValidDaysAsString(c)); } if (t.getIssued() != null) { if (t.getTicketClass() == Ticket.C_UNLIM_DAYS) { if (t.getTripSeqNumber() != 0 && t.getUseTillDate() != null) { Calendar toCal = (Calendar) t.getUseTillDate().clone(); toCal.add(Calendar.MINUTE, t.getFirstUseTime()); Calendar fromCal = (Calendar) toCal.clone(); fromCal.add(Calendar.DATE, -1 * t.getValidDays()); this.setTicket("t_from_datetime", String.format("%s", Ticket.DTF.format(fromCal.getTime()))); this.setTicket("t_to_datetime", String.format("%s", Ticket.DTF.format(toCal.getTime()))); } else if (t.getStartUseTill() != null) { this.setTicket("t_start_use_till", Ticket.DTF.format(t.getStartUseTill().getTime())); } } else { Calendar toCal = (Calendar) t.getIssued().clone(); toCal.add(Calendar.DATE, t.getValidDays()); this.setTicket("t_from_date", String.format("%s", Ticket.DF.format(t.getIssued().getTime()))); this.setTicket("t_to_date", String.format("%s", Ticket.DF.format(toCal.getTime()))); } } if (t.getTicketClass() != Ticket.C_UNLIM_DAYS) { if (t.getStartUseBefore() != null) { if (t.getIssued() != null) { Calendar tmpCal = (Calendar) t.getIssued().clone(); tmpCal.add(Calendar.DATE, t.getValidDays()); if (t.getStartUseBefore().after(tmpCal)) this.setTicket("t_start_use_before", t.getStartUseBeforeAsString()); } else this.setTicket("t_start_use_before", t.getStartUseBeforeAsString()); } } if (t.getStartUseTill() != null && t.getTicketClass() == Ticket.C_UNLIM_DAYS) { this.setTicket("t_start_use_till", Ticket.DTF.format(t.getStartUseTill().getTime())); } if (t.getPassesLeft() > 0) this.setTicket("t_trips_left", t.getPassesLeftAsString()); if ((t.getTurnstileEntered() != 0) || (t.getEntranceEntered() != 0)) { this.setTicket("t_trip_seq_number", t.getTripSeqNumbetAsString()); if (t.getTripStart() != null) { this.setTicket("t_trip_start_date", Ticket.DF.format(t.getTripStart().getTime())); this.setTicket("t_trip_start_time", Ticket.TF.format(t.getTripStart().getTime())); } if (t.getTurnstileEntered() != 0) { this.setTicket("t_station_id", t.getTurnstileEnteredAsString()); this.setTicket("t_station", t.getTurnstileDescAsHTML(c)); } else if (t.getEntranceEntered() != 0) { this.setTicket("t_station_id", t.getEntranceEnteredAsString()); this.setTicket("t_station", t.getStationDescAsHTML(c)); } this.setTicket("t_transport_type", t.getTransportTypeAsHTML(c)); } // TODO: move to web interface if (t.getTicketClass() == Ticket.C_90UNIVERSAL) { this.setTicket("t_90m_header_fake", " "); StringBuilder sb = new StringBuilder(); if (t.getT90TripTimeLeft() > 0) { sb.append(" "); sb.append(c.getString(R.string.t90m_trip_time_left)); sb.append(": "); sb.append(t.getReadableTime(t.getT90TripTimeLeft())); } else { sb.append(" "); sb.append(c.getString(R.string.t90m_trip_time_finished)); } sb.append('\n'); sb.append(" "); sb.append(c.getString(R.string.t90m_metro_trip_is)); sb.append(" "); if (t.getT90MCount() > 0) { sb.append(c.getString(R.string.t90m_metro_used)); } else { sb.append(c.getString(R.string.t90m_metro_trip_possible)); } sb.append('\n'); switch (t.getLayout()) { case 13: sb.append(" "); sb.append(c.getString(R.string.t90m_ground_count)); sb.append(": "); sb.append(t.getT90GCount()); sb.append('\n'); break; case 10: break; } if (t.getT90RelChangeTime() != 0) { sb.append(" "); sb.append(c.getString(R.string.t90m_change_time)); sb.append(": "); sb.append(Ticket.TF.format(t.getT90ChangeTime().getTime())); sb.append(String.format(" (%02d min)", t.getT90RelChangeTime())); sb.append('\n'); } this.setTicket("t_90m_details", sb.toString()); } this.setTicket("t_file_name", t.getFileName() + Ticket.FILE_EXT); if (t.getRealFileName() != null && !t.getRealFileName().equals(t.getFileName() + Ticket.FILE_EXT)) this.setTicket("t_real_file_name", t.getRealFileName()); if (d.getRemark().length() > 0) this.setTicket("t_note_text", d.getRemark()); this.setTicket("t_layout", t.getTicketLayoutAsString()); this.setTicket("t_app_id", t.getTicketAppIDAsString()); this.setTicket("t_type_id", t.getTicketTypeAsString()); this.setTicket("t_hash", t.getHashAsHexString()); this.setTicket("t_number", t.getTicketNumberAsString()); this.setTicket("t_ic_uid", d.getUIDAsString()); if (!t.isTicketFormatValid()) this.setTicket("t_dump_crc16", Ticket.getDumpCRC16AsHexString(t.getDump())); if (t.getParserError() != null && t.getParserError().length() != 0) this.setTicket("t_parser_error", "<font color=\"red\">Parser error:\n " + t.getParserError() + "</font>"); this.setTicket("i_manufacturer", d.getManufacturerAsHTML()); this.setTicket("i_chip_names", d.getChipNamesAsHTML()); this.setTicket("i_std_bytes", d.getChipCapacityAsHTML()); this.setTicket("i_read_pages", d.getPagesReadAsHTML()); this.setTicket("i_read_bytes", d.getBytesReadAsHTML()); this.setTicket("i_uid_hi", d.getUIDHiasHTML()); this.setTicket("i_uid_lo", d.getUIDLoasHTML()); this.setTicket("i_bcc0", d.getBCC0AsHTML()); this.setTicket("i_bcc1", d.getBCC1AsHTML()); this.setTicket("i_crc_status", d.getUIDCRCStatusAsHTML()); this.setTicket("i_otp", d.getOTPAsHTML()); if (d.isSAKNotEmpty()) this.setIC("i_sak", d.getSAKAsHTML()); if (d.isATQANotEmpty()) this.setIC("i_atqa", d.getATQAAsHTML()); if (d.isVERSIONNotEmpty()) this.setIC("i_get_version", d.getVERSIONAsHTML()); if (d.isCountersNotEmpty()) this.setIC("i_counters", d.getCountersAsHTML()); if (d.isSIGNNotEmpty()) this.setIC("i_read_sig", d.getSIGNAsHTML()); if (d.isAtechListNotEmpty()) this.setIC("i_tech", d.getATechAsHTML()); this.setDump(d.getDumpAsHTMLString()); this.displayMainScreen(wv); }