Check internet connection in android

Checking Network Connection

Before you perform any network operations, you must first check that are you connected to that network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below −

ConnectivityManager check = (ConnectivityManager) 
this.context.getSystemService(Context.CONNECTIVITY_SERVICE);  

Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();

The last thing you need to do is to check Connected State of the network. Its syntax is given below −

for (int i = 0; i<info.length; i++){
   if (info[i].getState() == NetworkInfo.State.CONNECTED){
      Toast.makeText(context, "Internet is connected
      Toast.LENGTH_SHORT).show();
   }
}