Skip to content

Instantly share code, notes, and snippets.

@whitfin
Last active January 4, 2016 20:49
Show Gist options
  • Save whitfin/8676497 to your computer and use it in GitHub Desktop.
Save whitfin/8676497 to your computer and use it in GitHub Desktop.
Simple class to control connection detection. Just call `isConnected()` with the Context, and an optional URL to ping.
package com.zackehh.example;
import java.net.URI;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Simple utilities to check connection to the Internet. Can check for a WiFi
* connection if run from a UI thread, but can be used to ping a site if
* run from a separate thread. Just add a URL string to the isConnected() call.
*
* @author Isaac Whitfield
* @version 30/08/2013
*/
public class ConnectUtils {
public static boolean isConnected(Context parent){
if(!checkNetwork(parent)){
return false;
}
return true;
}
public static boolean isConnected(Context parent, String url){
if(!checkNetwork(parent)){
return false;
}
if(!checkConnection(url)){
return false;
}
return true;
}
private static boolean checkNetwork(Context parent){
ConnectivityManager conMgr = (ConnectivityManager)parent.getSystemService(Context.CONNECTIVITY_SERVICE);
if(conMgr.getActiveNetworkInfo() != null){
NetworkInfo activeInfo = conMgr.getActiveNetworkInfo();
if(!activeInfo.isConnected() || !activeInfo.isAvailable()){
return false;
}
return true;
}
return false;
}
private static boolean checkConnection(String url){
try {
HttpGet requestTest = new HttpGet(new URI(url));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
DefaultHttpClient client = new DefaultHttpClient(params);
client.execute(requestTest);
return true;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment