How to Check Internet Connection Available or Not

How to Check Internet Connection Available or Not

Hello Friends !!

Today, We learn about how to check internet connection is available or not.

This Function is use when you work with Rest API, or any work with internet in your application.

So, First of all we need to create Object of Connectivity Manager.

ConnectivityManager is a class of inbuilt by android platform for check the current internet connection is available or not , it also notify when change the network state.

Ex :

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

Context.CONNECTIVITY_SERVICE is check the current system connection either if you using mobile data/WiFi.

When you  want use it more than one time then create one method which return Boolean object for return true either connection is establish  or false when not connected.

Now Compare the ConnectivityManager class object with condition for check.

Ex:

boolean connected=false;

if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else {
connected = false;
}

so the above condition return true/false for check with connection of your mobile data and also check the WiFi connection.

Finally Your method will be :

public boolean isNetworkCheck(){

boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else {
connected = false;
}
return connected;

}

Finally when we work with any component or hardware with our device then you need to get the permission in you AndroidManifiest.xml file:

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

 

So Enjoy Coding , Any query feel free to write here .

Thank you.

🙂

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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