Check internet connection status in android

Almost every android application these days require accessing internet for fetching and posting data. Posting and fetching data usually causes exceptions due unavailability of internet . Hence , to always good to check internet connection before starting tasks that requires  internet connection. Check this post if you want to how to make http connections.

You can also check the  kind of internet connection is available in handset.eg wifi or mobile data

The following code snippet will let you check internet availability and specify the type of internet connection available.

Step 1. Firstly  you need to add the following permission in the AndroidManifest.

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

Step 2: Use the following code to check internet status

private boolean isNetworkConnected() {
// checks for both mobile and wifi internet connection
boolean isConnectedWifi = false;
boolean isConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[]info = cm.getAllNetworkInfo();
for (NetworkInfo net : info) {
if (net.getTypeName().equalsIgnoreCase("WIFI"))
if (net.isConnected())
haveConnectedWifi = true;
if (net.getTypeName().equalsIgnoreCase("MOBILE"))
if (net.isConnected())
haveConnectedMobile = true;
}
return isConnectedWifi || isConnectedMobile;
}

Always remember to check to internet availability before performing any tasks that require internet .

Related Posts:

Making  http connection in android

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s