Android – check Internet connection
Problem: How To check whether the device has network connection or not?
Solution:
public static boolean checkNetworkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable())
return true;
else
return false;
}
Update:
This will work for both Emulator & Device. I got this helpful information from this SO answer.
connected = (connMgr.getActiveNetworkInfo() != null && connMgr.getActiveNetworkInfo().isAvailable() && connMgr.getActiveNetworkInfo().isConnected() )
Note the use of isAvailable – without this isConnected can return TRUE even when WIFI is disabled.
