Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 24th, 2012  |  syntax: None  |  size: 1.86 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Checking whether Internet can be accessed without the user having to log in or agree to terms first via the browser
  2. public class InternetCheck {
  3.  
  4.         public static boolean ActiveInternetExists() {
  5.  
  6.             boolean internetAccessExists = false;
  7.  
  8.             //make the android homepage as the requested url
  9.             //this is a critical decision point.
  10.             //the belief here is that this url can be accessed all around the world
  11.             String urlToBeAccessed = "http://www.android.com/";
  12.  
  13.             final int TIMEOUT_VALUE_IN_MILLISECONDS = 6000;
  14.  
  15.             URL url;
  16.             HttpURLConnection urlConnection = null;
  17.  
  18.             try {
  19.  
  20.                 url = new URL(urlToBeAccessed);
  21.                 urlConnection = (HttpURLConnection) url.openConnection();
  22.  
  23.                 //set the respective timeouts for the connection
  24.                 urlConnection.setConnectTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
  25.                 urlConnection.setReadTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
  26.  
  27.                 //the redirect check is valid only after the response headers have been received
  28.                 //this is triggered by the getInputStream() method
  29.                 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  30.  
  31.                 //check if the urls of the requested and landing pages are equal
  32.                 //if yes, then we don't have a redirect
  33.                 if (url.getHost().equals(urlConnection.getURL().getHost()))
  34.                     internetAccessExists =  true;
  35.             }
  36.  
  37.             //any sort of exception is considered as a redirect.
  38.             //more specific exceptions such as SocketTimeOutException and IOException can be handled as well
  39.             catch (Exception e) {
  40.             }
  41.             finally {
  42.                 urlConnection.disconnect();
  43.             }
  44.  
  45.             return internetAccessExists;
  46.         }
  47.  
  48. }