Check Internet Connectivity in android

Hey Friends,

Here is another android code snippet on how to check internet connectivity in android. In your application before fetching any live data from the server it is best practice to check internet connectivity first. This step will help you to make sure the error occurs in your application is not because of your server but because of device's internet connectivity.

If you are a beginner you must have to practice to do check internet connectivity in device, and below code will help you out with the same.

This code snippet will help you to check internet connectivity before doing anything you can check using this small enough of code.

Paste below code in your Mainactivity.java file.

public static boolean checkInternet(Context ctx) {
	ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(ctx.CONNECTIVITY_SERVICE);
	if (connectivityManager != null) {
		NetworkInfo networkInf = connectivityManager.getActiveNetworkInfo();
		if (networkInf != null && networkInf.isConnected()
				&& networkInf.isConnectedOrConnecting()
				&& networkInf.isAvailable()) {
			return true;
		}
	}
	return false;
}

For this you need to add below code in your menifest.xml file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>

After this you can use your method checkInternet(context) anywhere in your activity class it will return true if internet is connected false if no internet connection in the device.
One Example is here:-

if(checkInternet(context)){
	//internet is connected
}else{
	//internet is not connected
}

Happy Coding!
Thanks.

Comments