Friday, January 28, 2011

Check Android network connection sample code

Chances are if you're building an Android app, you're going to be using the device's data connection. After all, the beauty of these things is having the power of the internet at your fingertips. You have to be careful though when building apps to always for the existence of an active connection. Failure to do so and then trying to fetch data could result in a negative user experience or possibly even crash.



Luckily, there's an easy way to check for data connections prior to making calls so you can either proceed or handle gracefully. The sample class below provides everything you need. Just insert into your project and call when necessary...







public class Networking {
/*
*@return boolean return true if the application can access the internet
*/
public static boolean isNetworkAvailable(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) {
return true;
}
}
}
}
return false;
}
}