Here is the method I use:
public boolean isNetworkAvailable(final Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
Even better, check to make sure it is "connected":
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Here is how to use the method:
if (isNetworkAvailable(context)) {
// code here
} else {
// code
}
Permission needed:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />