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;
}





Recent Posts:
Hello there!,

You are using AdBlocker!

I am an independent developer trying to help fellow developers and students to resolve issues faced on a day-to-day basis, we 'Code to Care' . There is a lot of expenses involved in hosting and managing a website that's the reason we have ads.

A humble request to you to disable adBlocker on Code2care.org and support us pay our bills.

Thanks,
Cod2ecare - Line's of code for change.

To see contents reload page after unblocking
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.