Method to check internet connectivity in android

Some times we need to check internet connection status of device when we perform any network tasks using our application in android application development.

Below is a simple method to check internet connectivity in android.

public static boolean isInternetPresent(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;
}

And here is an example how to use it in your code.

if(isInternetPresent(context)){
// perform your network task here
}else {
// show internet error message here
}

 

(Visited 101 times, 1 visits today)