Check Internet Connection WIFI 4G is active on Android Programmatically

It is always preferred to check Internet Connection before fetching/posting data over http while working with Android Application.

ConnectivityManager class is used to check network connectivity. This class also notifies applications when network connectivity changes say from 2G to 4G or WiFi.

ConnectivityManager class responsibilities are :

  • To Monitor network connections (Wi-Fi, GPRS, 2G,3G, etc.)
  • Send Broadcast intents when network connectivity changes (say Mobile to Wifi)
  • Attempt to fail over to another network when connectivity to a network is lost
  • Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks.

Below method check if any of the network (Data Plan ie. Mobile or Wifi ) is active on the Android Device and returns a boolean value.

//Check if Internet Network is active
 private boolean checkNetwork() {

 boolean wifiDataAvailable = false;
 boolean mobileDataAvailable = false;

ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();

for (NetworkInfo netInfo : networkInfo) {
  if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
    if (netInfo.isConnected())
        wifiDataAvailable = true;
    if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
        if (netInfo.isConnected())
        mobileDataAvailable = true;
    return wifiDataAvailable || mobileDataAvailable;