List of usage examples for android.webkit WebViewClient WebViewClient
WebViewClient
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 . ja va 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")) { 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); }
From source file:com.pagenews.zhihudaily.detail.DetailFragment.java
@Override public void initViews(View view) { refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout); ////from w w w. j ava 2 s.co m refreshLayout.setColorSchemeResources(R.color.colorPrimary); webView = (WebView) view.findViewById(R.id.web_view); webView.setScrollbarFadingEnabled(true); DetailActivity activity = (DetailActivity) getActivity(); activity.setSupportActionBar((Toolbar) view.findViewById(R.id.toolbar)); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); imageView = (ImageView) view.findViewById(R.id.image_view); scrollView = (NestedScrollView) view.findViewById(R.id.scrollView); toolbarLayout = (CollapsingToolbarLayout) view.findViewById(R.id.toolbar_layout); //js webView.getSettings().setJavaScriptEnabled(true); //,???? webView.getSettings().setBuiltInZoomControls(false); // webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //?DOM storage API webView.getSettings().setDomStorageEnabled(true); //?application Cache webView.getSettings().setAppCacheEnabled(false); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { presenter.openUrl(view, url); return true; } }); }
From source file:com.androzic.waypoint.WaypointDetails.java
@SuppressLint("NewApi") private void updateWaypointDetails(double lat, double lon) { Androzic application = Androzic.getApplication(); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.getSupportActionBar().setTitle(waypoint.name); View view = getView();/*from ww w . j a v a 2 s . co m*/ final TextView coordsView = (TextView) view.findViewById(R.id.coordinates); coordsView.requestFocus(); coordsView.setTag(Integer.valueOf(StringFormatter.coordinateFormat)); coordsView.setText(StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude)); coordsView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int format = ((Integer) coordsView.getTag()).intValue() + 1; if (format == 5) format = 0; coordsView.setText(StringFormatter.coordinates(format, " ", waypoint.latitude, waypoint.longitude)); coordsView.setTag(Integer.valueOf(format)); } }); if (waypoint.altitude != Integer.MIN_VALUE) { ((TextView) view.findViewById(R.id.altitude)) .setText("\u2336 " + StringFormatter.elevationH(waypoint.altitude)); view.findViewById(R.id.altitude).setVisibility(View.VISIBLE); } else { view.findViewById(R.id.altitude).setVisibility(View.GONE); } if (waypoint.proximity > 0) { ((TextView) view.findViewById(R.id.proximity)) .setText("~ " + StringFormatter.distanceH(waypoint.proximity)); view.findViewById(R.id.proximity).setVisibility(View.VISIBLE); } else { view.findViewById(R.id.proximity).setVisibility(View.GONE); } double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude); double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude); bearing = application.fixDeclination(bearing); String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing); ((TextView) view.findViewById(R.id.distance)).setText(distance); ((TextView) view.findViewById(R.id.waypointset)).setText(waypoint.set.name); if (waypoint.date != null) { view.findViewById(R.id.date_row).setVisibility(View.VISIBLE); ((TextView) view.findViewById(R.id.date)) .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " " + DateFormat.getTimeFormat(activity).format(waypoint.date)); } else { view.findViewById(R.id.date_row).setVisibility(View.GONE); } if ("".equals(waypoint.description)) { view.findViewById(R.id.description_row).setVisibility(View.GONE); } else { WebView description = (WebView) view.findViewById(R.id.description); String descriptionHtml; try { TypedValue tv = new TypedValue(); Theme theme = activity.getTheme(); Resources resources = getResources(); theme.resolveAttribute(android.R.attr.textColorPrimary, tv, true); int secondaryColor = resources.getColor(tv.resourceId); String css = String.format( "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n", (secondaryColor & 0x00FFFFFF)); descriptionHtml = css + waypoint.description; description.setWebViewClient(new WebViewClient() { @SuppressLint("NewApi") @Override public void onPageFinished(WebView view, String url) { view.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } }); description.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } catch (Resources.NotFoundException e) { description.setBackgroundColor(Color.LTGRAY); descriptionHtml = waypoint.description; } WebSettings settings = description.getSettings(); settings.setDefaultTextEncodingName("utf-8"); settings.setAllowFileAccess(true); Uri baseUrl = Uri.fromFile(new File(application.dataPath)); description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null); view.findViewById(R.id.description_row).setVisibility(View.VISIBLE); } }
From source file:org.openhab.habdroid.ui.OpenHABWidgetSettingsAdapter.java
@Override public View getView(int position, View convertView, ViewGroup parent) { /* TODO: This definitely needs some huge refactoring */// w ww . j av a2s . c o m final int pos = position; RelativeLayout widgetView; TextView labelTextView; ImageView roomEditView; int widgetLayout = 0; OpenHABWidget openHABWidget = getItem(position); switch (this.getItemViewType(position)) { case TYPE_FRAME: widgetLayout = R.layout.openhabwidgetlist_frameitem; break; case TYPE_GROUP: widgetLayout = R.layout.openhabwidget_settings_item; break; case TYPE_IMAGE: widgetLayout = R.layout.openhabwidgetlist_imageitem; break; case TYPE_CHART: widgetLayout = R.layout.openhabwidgetlist_chartitem; break; case TYPE_VIDEO: widgetLayout = R.layout.openhabwidgetlist_videoitem; break; case TYPE_WEB: widgetLayout = R.layout.openhabwidgetlist_webitem; break; default: widgetLayout = R.layout.openhabwidget_settings_item; break; } if (convertView == null) { widgetView = new RelativeLayout(getContext()); String inflater = Context.LAYOUT_INFLATER_SERVICE; LayoutInflater vi; vi = (LayoutInflater) getContext().getSystemService(inflater); vi.inflate(widgetLayout, widgetView, true); } else { widgetView = (RelativeLayout) convertView; } switch (getItemViewType(position)) { case TYPE_FRAME: labelTextView = (TextView) widgetView.findViewById(R.id.framelabel); if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); widgetView.setClickable(false); if (openHABWidget.getLabel().length() > 0) { // hide empty frames widgetView.setVisibility(View.VISIBLE); labelTextView.setVisibility(View.VISIBLE); } else { widgetView.setVisibility(View.GONE); labelTextView.setVisibility(View.GONE); } break; case TYPE_IMAGE: MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage); imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false); if (openHABWidget.getRefresh() > 0) { imageImage.setRefreshRate(openHABWidget.getRefresh()); refreshImageList.add(imageImage); } break; case TYPE_CHART: MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage); OpenHABItem chartItem = openHABWidget.getItem(); Random random = new Random(); String chartUrl = ""; if (chartItem.getType().equals("GroupItem")) { chartUrl = openHABBaseUrl + "rrdchart.png?groups=" + chartItem.getName() + "&period=" + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt()); } Log.i("OpenHABWidgetAdapter", "Chart url = " + chartUrl); chartImage.setImageUrl(chartUrl, false); // TODO: This is quite dirty fix to make charts look full screen width on all displays ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams(); int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay().getWidth(); chartLayoutParams.height = (int) (screenWidth / 1.88); chartImage.setLayoutParams(chartLayoutParams); if (openHABWidget.getRefresh() > 0) { chartImage.setRefreshRate(openHABWidget.getRefresh()); refreshImageList.add(chartImage); } Log.i("OpenHABWidgetAdapter", "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height); break; case TYPE_VIDEO: VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo); Log.i("OpenHABWidgetAdapter", "Opening video at " + openHABWidget.getUrl()); // TODO: This is quite dirty fix to make video look maximum available size on all screens WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams(); videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77); videoVideo.setLayoutParams(videoLayoutParams); // We don't have any event handler to know if the VideoView is on the screen // so we manage an array of all videos to stop them when user leaves the page if (!videoWidgetList.contains(videoVideo)) videoWidgetList.add(videoVideo); // Start video if (!videoVideo.isPlaying()) { videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl())); videoVideo.start(); } Log.i("OpenHABWidgetAdapter", "Video height is " + videoVideo.getHeight()); break; case TYPE_WEB: WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb); if (openHABWidget.getHeight() > 0) { ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams(); webLayoutParams.height = openHABWidget.getHeight() * 80; webWeb.setLayoutParams(webLayoutParams); } webWeb.setWebViewClient(new WebViewClient()); webWeb.loadUrl(openHABWidget.getUrl()); break; default: labelTextView = (TextView) widgetView.findViewById(R.id.itemlabel); roomEditView = (ImageView) widgetView.findViewById(R.id.editimg); if (null != roomEditView) { roomEditView.setVisibility(View.VISIBLE); roomEditView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (null != listItemListener) listItemListener.onEditClickListener(pos); } }); } if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); MySmartImageView sliderImage = (MySmartImageView) widgetView.findViewById(R.id.itemimage); sliderImage.setImageUrl(openHABBaseUrl + "images/" + openHABWidget.getIcon() + ".png"); break; } LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider); if (dividerLayout != null) { if (position < this.getCount() - 1) { if (this.getItemViewType(position + 1) == TYPE_FRAME) { dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets } else { dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others } } else { // last widget in the list, hide divider dividerLayout.setVisibility(View.GONE); } } return widgetView; }
From source file:com.stoutner.privacybrowser.MainWebViewActivity.java
@Override // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers. @SuppressLint("SetJavaScriptEnabled") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_coordinatorlayout); // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21. Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar); setSupportActionBar(supportAppBar);// www. j ava 2 s.c om final ActionBar appBar = getSupportActionBar(); // This is needed to get rid of the Android Studio warning that appBar might be null. assert appBar != null; // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar. appBar.setCustomView(R.layout.url_bar); appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); // Set the "go" button on the keyboard to load the URL in urlTextBox. urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox); urlTextBox.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button, load the URL. if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Load the URL into the mainWebView and consume the event. try { loadUrlFromTextBox(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // If the enter key was pressed, consume the event. return true; } else { // If any other key was pressed, do not consume the event. return false; } } }); final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout); // Implement swipe to refresh swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null. swipeToRefresh.setColorSchemeResources(R.color.blue); swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mainWebView.reload(); } }); mainWebView = (WebView) findViewById(R.id.mainWebView); // Create the navigation drawer. drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); // The DrawerTitle identifies the drawer in accessibility mode. drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer)); // Listen for touches on the navigation menu. final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null. navigationView.setNavigationItemSelectedListener(this); // drawerToggle creates the hamburger icon at the start of the AppBar. drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation); mainWebView.setWebViewClient(new WebViewClient() { // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps. @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { mainWebView.loadUrl(url); return true; } // Update the URL in urlTextBox when the page starts to load. @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { urlTextBox.setText(url); } // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load. @Override public void onPageFinished(WebView view, String url) { formattedUrlString = url; // Only update urlTextBox if the user is not typing in it. if (!urlTextBox.hasFocus()) { urlTextBox.setText(formattedUrlString); } } }); mainWebView.setWebChromeClient(new WebChromeClient() { // Update the progress bar when a page is loading. @Override public void onProgressChanged(WebView view, int progress) { // Make sure that appBar is not null. if (appBar != null) { ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar); progressBar.setProgress(progress); if (progress < 100) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); //Stop the SwipeToRefresh indicator if it is running swipeToRefresh.setRefreshing(false); } } } // Set the favorite icon when it changes. @Override public void onReceivedIcon(WebView view, Bitmap icon) { // Save a copy of the favorite icon for use if a shortcut is added to the home screen. favoriteIcon = icon; // Place the favorite icon in the appBar if it is not null. if (appBar != null) { ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView() .findViewById(R.id.favoriteIcon); imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true)); } } // Enter full screen video @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (appBar != null) { appBar.hide(); } // Show the fullScreenVideoFrameLayout. assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null. fullScreenVideoFrameLayout.addView(view); fullScreenVideoFrameLayout.setVisibility(View.VISIBLE); // Hide the mainWebView. mainWebView.setVisibility(View.GONE); // Hide the ad if this is the free flavor. BannerAd.hideAd(adView); /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen. * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen. * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them. */ // Set the one flag supported by API >= 14. view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); // Set the two flags that are supported by API >= 16. if (Build.VERSION.SDK_INT >= 16) { view.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } // Set all three flags that are supported by API >= 19. if (Build.VERSION.SDK_INT >= 19) { view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } // Exit full screen video public void onHideCustomView() { if (appBar != null) { appBar.show(); } // Show the mainWebView. mainWebView.setVisibility(View.VISIBLE); // Show the ad if this is the free flavor. BannerAd.showAd(adView); // Hide the fullScreenVideoFrameLayout. assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null. fullScreenVideoFrameLayout.removeAllViews(); fullScreenVideoFrameLayout.setVisibility(View.GONE); } }); // Allow the downloading of files. mainWebView.setDownloadListener(new DownloadListener() { // Launch the Android download manager when a link leads to a download. @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url)); // Add the URL as the description for the download. requestUri.setDescription(url); // Show the download notification after the download is completed. requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // Initiate the download and display a Snackbar. downloadManager.enqueue(requestUri); Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT) .show(); } }); // Allow pinch to zoom. mainWebView.getSettings().setBuiltInZoomControls(true); // Hide zoom controls. mainWebView.getSettings().setDisplayZoomControls(false); // Initialize the default preference values the first time the program is run. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Get the shared preference values. SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Set JavaScript initial status. The default value is false. javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false); mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled); // Initialize cookieManager. cookieManager = CookieManager.getInstance(); // Set cookies initial status. The default value is false. firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false); cookieManager.setAcceptCookie(firstPartyCookiesEnabled); // Set third-party cookies initial status if API >= 21. The default value is false. if (Build.VERSION.SDK_INT >= 21) { thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false); cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled); } // Set DOM storage initial status. The default value is false. domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false); mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled); // Set the user agent initial status. String userAgentString = savedPreferences.getString("user_agent", "Default user agent"); switch (userAgentString) { case "Default user agent": // Do nothing. break; case "Custom user agent": // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0". mainWebView.getSettings() .setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0")); break; default: // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0". mainWebView.getSettings() .setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0")); break; } // Set the initial string for JavaScript disabled search. if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=") .equals("Custom URL")) { // Get the custom URL string. The default is "". javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", ""); } else { // Use the string from javascript_disabled_search. javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q="); } // Set the initial string for JavaScript enabled search. if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=") .equals("Custom URL")) { // Get the custom URL string. The default is "". javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", ""); } else { // Use the string from javascript_enabled_search. javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q="); } // Set homepage initial status. The default value is "https://www.duckduckgo.com". homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com"); // Set swipe to refresh initial status. The default is true. swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true); swipeToRefresh.setEnabled(swipeToRefreshEnabled); // Get the intent information that started the app. final Intent intent = getIntent(); if (intent.getData() != null) { // Get the intent data and convert it to a string. final Uri intentUriData = intent.getData(); formattedUrlString = intentUriData.toString(); } // If formattedUrlString is null assign the homepage to it. if (formattedUrlString == null) { formattedUrlString = homepage; } // Load the initial website. mainWebView.loadUrl(formattedUrlString); // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing. adView = findViewById(R.id.adView); BannerAd.requestAd(adView); }
From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java
void handleSendSubject(Intent intent) { final String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); final String sharedSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); final String sharedBy = getString(R.string.shared_by_diaspora_android); if (sharedSubject != null) { webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { webView.setWebViewClient(new WebViewClient() { @Override/*from w w w .ja va 2s . com*/ public boolean shouldOverrideUrlLoading(WebView view, String url) { finish(); Intent i = new Intent(ShareActivity.this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); return false; } }); webView.loadUrl("javascript:(function() { " + "document.getElementsByTagName('textarea')[0].style.height='110px'; " + "document.getElementsByTagName('textarea')[0].innerHTML = '**" + sharedSubject + "** " + sharedText + " " + sharedBy + "'; " + " if(document.getElementById(\"main_nav\")) {" + " document.getElementById(\"main_nav\").parentNode.removeChild(" + " document.getElementById(\"main_nav\"));" + " } else if (document.getElementById(\"main-nav\")) {" + " document.getElementById(\"main-nav\").parentNode.removeChild(" + " document.getElementById(\"main-nav\"));" + " }" + "})();"); } }); } }
From source file:com.company.millenium.iwannask.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //GPS//from w w w. ja va 2s .co m locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(this); } } public void onStatusChanged(String string, int integer, Bundle bundle) { } public void onProviderEnabled(String string) { } public void onProviderDisabled(String string) { } }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener); } int delay = 30000; // delay for 30 sec. int period = 3000000; // repeat every 5.3min. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(locationListener); } } }, delay, period); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); Intent mIntent = getIntent(); URL = Constants.SERVER_URL; if (mIntent.hasExtra("url")) { myWebView = null; startActivity(getIntent()); String url = mIntent.getStringExtra("url"); URL = Constants.SERVER_URL + url; } CookieSyncManager.createInstance(this); CookieSyncManager.getInstance().startSync(); myWebView = (WebView) findViewById(R.id.webview); myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath()); myWebView.getSettings().setGeolocationEnabled(true); WebSettings webSettings = myWebView.getSettings(); webSettings.setUseWideViewPort(false); if (!DetectConnection.checkInternetConnection(this)) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); showNoConnectionDialog(this); } else { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } webSettings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new webappinterface(this), "android"); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER); //location test webSettings.setAppCacheEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { CookieSyncManager.getInstance().sync(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); // Ignore SSL certificate errors } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals(Constants.HOST) || Uri.parse(url).getHost().equals(Constants.WWWHOST)) { // This is my web site, so do not override; let my WebView load // the page return false; } // Otherwise, the link is not for a page on my site, so launch // another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }); myWebView.setWebChromeClient(new WebChromeClient() { public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } @Override public void onPermissionRequest(final PermissionRequest request) { Log.d(TAG, "onPermissionRequest"); runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void run() { if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) { request.grant(request.getResources()); } else { request.deny(); } } }); } public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { // Double check that we don't have any existing callbacks if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; // Set up the take picture intent Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); } catch (IOException ex) { // Error occurred while creating the File Log.e(TAG, "Unable to create Image File", ex); } // Continue only if the File was successfully created if (photoFile != null) { mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } // Set up the intent to get an existing image Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("image/*"); // Set up the intents for the Intent chooser Intent[] intentArray; if (takePictureIntent != null) { intentArray = new Intent[] { takePictureIntent }; } else { intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); return true; } }); // setContentView(myWebView); // myWebView.loadUrl(URL); myWebView.loadUrl(URL); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // mRegistrationProgressBar.setVisibility(ProgressBar.GONE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); } }; //CookieManager mCookieManager = CookieManager.getInstance(); //Boolean hasCookies = mCookieManager.hasCookies(); //while(!hasCookies); if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); //intent.putExtra("session", session); startService(intent); } Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true); if (isFirstRun) { //show start activity startActivity(new Intent(MainActivity.this, MyIntro.class)); } //if (!isOnline()) // showNoConnectionDialog(this); getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit(); //Pull-to-refresh mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container); mSwipeRefreshLayout.setOnRefreshListener(this); }
From source file:com.irccloud.android.activity.ImageViewerActivity.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override/*from w w w .java 2 s .c o m*/ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHideTimer = new Timer("actionbar-hide-timer"); if (savedInstanceState == null) overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out); setContentView(R.layout.activity_imageviewer); toolbar = (Toolbar) findViewById(R.id.toolbar); try { setSupportActionBar(toolbar); } catch (Throwable t) { } if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 19) getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); else if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams(); int resid = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resid > 0) lp.topMargin = getResources().getDimensionPixelSize(resid); else lp.topMargin = getResources().getDimensionPixelSize(R.dimen.status_bar_height); toolbar.setLayoutParams(lp); } getSupportActionBar().setTitle("Image Viewer"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_translucent)); mImage = (WebView) findViewById(R.id.image); mImage.setBackgroundColor(0); mImage.addJavascriptInterface(new JSInterface(), "Android"); mImage.getSettings().setBuiltInZoomControls(true); if (Integer.parseInt(Build.VERSION.SDK) >= 19) mImage.getSettings().setDisplayZoomControls(false); mImage.getSettings().setJavaScriptEnabled(true); mImage.getSettings().setLoadWithOverviewMode(true); mImage.getSettings().setUseWideViewPort(true); mImage.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { mProgress.setProgress(newProgress); } }); mImage.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mSpinner.setVisibility(View.GONE); mProgress.setVisibility(View.GONE); mImage.setVisibility(View.VISIBLE); hide_actionbar(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { fail(); } @Override public void onLoadResource(WebView view, String url) { mSpinner.setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); } }); mSpinner = (ProgressBar) findViewById(R.id.spinner); mProgress = (ProgressBar) findViewById(R.id.progress); if (getIntent() != null && getIntent().getDataString() != null) { String url = getIntent().getDataString().replace(getResources().getString(R.string.IMAGE_SCHEME), "http"); String lower = url.toLowerCase().replace("https://", "").replace("http://", ""); if (lower.startsWith("www.dropbox.com/")) { if (lower.startsWith("www.dropbox.com/s/")) { url = url.replace("://www.dropbox.com/s/", "://dl.dropboxusercontent.com/s/"); } else { url = url + "?dl=1"; } } else if ((lower.startsWith("d.pr/i/") || lower.startsWith("droplr.com/i/")) && !lower.endsWith("+")) { url += "+"; } else if (lower.startsWith("imgur.com/") || lower.startsWith("www.imgur.com/")) { String id = url.replace("https://", "").replace("http://", ""); id = id.substring(id.indexOf("/") + 1); if (!id.contains("/") && id.length() > 0) { new ImgurImageTask().execute(id); } else if (id.startsWith("gallery/") && id.length() > 8) { new ImgurGalleryTask().execute(id.substring(8)); } else { fail(); } return; } else if (lower.startsWith("flickr.com/") || lower.startsWith("www.flickr.com/")) { new OEmbedTask().execute("https://www.flickr.com/services/oembed/?format=json&url=" + url); return; } else if (lower.startsWith("instagram.com/") || lower.startsWith("www.instagram.com/") || lower.startsWith("instagr.am/") || lower.startsWith("www.instagr.am/")) { new OEmbedTask().execute("http://api.instagram.com/oembed?url=" + url); return; } else if (lower.startsWith("cl.ly")) { new ClLyTask().execute(url); return; } else if (url.contains("/wiki/File:")) { new WikiTask().execute(url.replace("/wiki/", "/w/api.php?action=query&format=json&prop=imageinfo&iiprop=url&titles=")); } else if (lower.startsWith("leetfiles.com/") || lower.startsWith("www.leetfiles.com/")) { url = url.replace("www.", "").replace("leetfiles.com/image/", "i.leetfiles.com/").replace("?id=", ""); } else if (lower.startsWith("leetfil.es/") || lower.startsWith("www.leetfil.es/")) { url = url.replace("www.", "").replace("leetfil.es/image/", "i.leetfiles.com/").replace("?id=", ""); } loadImage(url); } else { finish(); } }
From source file:com.microsoft.windowsazure.mobileservices.LoginManager.java
/** * Creates the UI for the interactive authentication process * /*from w w w .j av a 2 s . c om*/ * @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 */ private void showLoginUI(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; 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.sahildave.snackbar.SnackBar.java
private View addLargeContainer(MessageType messageType, String inputUrl) { View v = activity.getLayoutInflater().inflate(R.layout.usb_large_container, null); WebView webView = (WebView) v.findViewById(R.id.snackWebview); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override// w ww .j a va 2 s . c om public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); webView.loadUrl(inputUrl); v.setTag(messageType); addToView(v); return v; }