
Untitled
By: a guest on
May 24th, 2012 | syntax:
None | size: 1.86 KB | hits: 10 | expires: Never
Checking whether Internet can be accessed without the user having to log in or agree to terms first via the browser
public class InternetCheck {
public static boolean ActiveInternetExists() {
boolean internetAccessExists = false;
//make the android homepage as the requested url
//this is a critical decision point.
//the belief here is that this url can be accessed all around the world
String urlToBeAccessed = "http://www.android.com/";
final int TIMEOUT_VALUE_IN_MILLISECONDS = 6000;
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlToBeAccessed);
urlConnection = (HttpURLConnection) url.openConnection();
//set the respective timeouts for the connection
urlConnection.setConnectTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
urlConnection.setReadTimeout(TIMEOUT_VALUE_IN_MILLISECONDS);
//the redirect check is valid only after the response headers have been received
//this is triggered by the getInputStream() method
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//check if the urls of the requested and landing pages are equal
//if yes, then we don't have a redirect
if (url.getHost().equals(urlConnection.getURL().getHost()))
internetAccessExists = true;
}
//any sort of exception is considered as a redirect.
//more specific exceptions such as SocketTimeOutException and IOException can be handled as well
catch (Exception e) {
}
finally {
urlConnection.disconnect();
}
return internetAccessExists;
}
}