Check if internet is available in Android

Many time in the Android app we need to fetch data from any webservices in JSON or XML or in any other format but during unavailability of internet we need to display specific message like no internet available or show offline data.

For that we need to use ConnectivityManager system service as follows.

ConnectivityManager cm = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);

Then we can get network information from above ConnectivityManager as follows using NetworkInfo.

NetworkInfo ni = cm.getActiveNetworkInfo();

Now this NetworkInfo have the following network states displyed in following table.

NetworkInfo.State CONNECTED
NetworkInfo.State CONNECTING
NetworkInfo.State DISCONNECTED
NetworkInfo.State SUSPENDED
NetworkInfo.State UNKNOWN

Now we have to check for the connected state of the network.

ni.getState() == NetworkInfo.State.CONNECTED;

From the above conclusion, finally we have come up with the following function that directly checks for the availability of the internet.

public boolean isNetworkAvailable() {
	ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo ni = cm.getActiveNetworkInfo();
	return ni != null && ni.getState() == NetworkInfo.State.CONNECTED;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s