Created
January 22, 2014 06:13
-
-
Save laaptu/8554175 to your computer and use it in GitHub Desktop.
Checking for internet connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static boolean isConnectedToInternet(Context context) { | |
if (isConnectingToInternet(context)) { | |
return isNetworkAvailable(); | |
} | |
return false; | |
} | |
public static boolean isConnectingToInternet(Context context) { | |
ConnectivityManager connectivity = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
if (connectivity != null) { | |
NetworkInfo[] info = connectivity.getAllNetworkInfo(); | |
if (info != null) | |
for (int i = 0; i < info.length; i++) | |
if (info[i].getState() == NetworkInfo.State.CONNECTED | |
&& info[i].isConnected()) { | |
return true; | |
} | |
} | |
return false; | |
} | |
public static boolean isNetworkAvailable() { | |
String TAG = "sometest"; | |
HttpGet httpGet = new HttpGet("http://www.google.com"); | |
HttpParams httpParameters = new BasicHttpParams(); | |
// Set the timeout in milliseconds until a connection is established. | |
// The default value is zero, that means the timeout is not used. | |
int timeoutConnection = 3000; | |
HttpConnectionParams.setConnectionTimeout(httpParameters, | |
timeoutConnection); | |
// Set the default socket timeout (SO_TIMEOUT) | |
// in milliseconds which is the timeout for waiting for data. | |
int timeoutSocket = 5000; | |
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); | |
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); | |
try { | |
Log.d(TAG, "Checking network connection..."); | |
httpClient.execute(httpGet); | |
return true; | |
} catch (ClientProtocolException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
Log.d(TAG, "Connection unavailable"); | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment