Home > Researches > Android – Detecting Internet Connection

Android – Detecting Internet Connection

Currently I’m working on an application which involves the network access, and one of the steps to be done is to check the internet connection.

In this article we will take a look on how to detect if there is or not internet connection, and display an AlertDialog with an appropriate message:

Android No Internet Connection

The class responsable for querying the state of network connectivity is the ConnectivityManager. The primary responsibilities of this class are to:

  1. Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
  2. Send broadcast intents when network connectivity changes
  3. Attempt to “fail over” to another network when connectivity to a network is lost
  4. Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks

An instance of this class can be retrieved by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE);

 

1. Create a new project in Eclipse:
Project: InternetConnection
Activity: InternetConnectionActivity

2. In order to query the state of network, the ACCESS_NETWORK_STATE permission must be specified in the  AndroidManifest file (otherwise you’ll get a security exception).

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

 

3. Detecting the internet connection

Our method of interest from the ConnectivityManager class is the getActiveNetworkInfo() method which returns an object of type NetworkInfo, through we can check if we are online or not.

Open the InternetConnectionActivity and just after the onCreate() method, add the following new method:

public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();

if (ni != null && ni.isConnected())
  return true;
else
  return false;
}

Note that it’s important to check the ni object if it’s not null, otherwise, if the connection is not available an exception is thrown.

 

4.  Creating an AlertDialog

To create an AlertDialog, the onCreateDialog() method should be overridden checking for an id and taking the appropriate actions. (Later, when we you’ll want to display the dialog, the showDialog(DIALOG_ID); should be called with the appropriate dialog id.)


@Override
protected Dialog onCreateDialog(int id) {
  Dialog dialog = null;
  switch (id) {
  case DIALOG_ERROR_CONNECTION:
    AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
    errorDialog.setTitle("Error");
    errorDialog.setMessage("No internet connection.");
    errorDialog.setNeutralButton("OK",
    new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {
        dialog.dismiss();
      }
    });

   AlertDialog errorAlert = errorDialog.create();
   return errorAlert;

  default:
    break;
  }
return dialog;
}

The DIALOG_ERROR_CONNECTION variable is a static variable that should be defined in your Activity:


public class InternetConnection extends Activity {
static final int DIALOG_ERROR_CONNECTION = 1;

.......

}

 

5. Putting all them together

Now that we have the necessary methods for detecting internet connection and creating an AlertDialog, let’s add some logic to our program and put these methods interact together in the onCreate().

Edit the onCreate() method to look like this:


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (!isOnline(this)) {
  showDialog(DIALOG_ERROR_CONNECTION); //displaying the created dialog.
} else {
  //Internet available. Do what's required when internet is available.
}

}

 

And the last thing… in order to properly test the internet connection, disable the internet from the emulator: Settings -> Wireless & Networks -> Mobile Networks -> Data Enabled, not from you computer local area connection. This is because even if you turn off the internet from your computer, but don’t turn it off from emulator, the isConnected() method will return true.

About these ads
  1. January 13, 2012 at 3:24 am

    $author you have awesome blog

  2. March 10, 2012 at 9:59 pm

    test

  3. March 20, 2012 at 10:31 am

    its not working for me .please help me …..

  4. July 13, 2012 at 12:07 pm

    Hi,
    For me , first activity opened and when i click connect button it shows ” Force to shutdown” why so ? How do i need to check Internet access in Android and by the way “My question is , ” When i click button in one page , it should navigate to another in Android by displaying http://www.google.com .. So what are all the steps should i do still can you temme?

  5. August 2, 2012 at 6:13 am

    I tried in 2 ways

    First

    ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ) {

    //Do something in here when we are connected

    }
    else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {

    }

    Second

    ConnectivityManager ConMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = ConMgr.getActiveNetworkInfo();
    if(netInfo != null) {

    } else{

    }

    But i’m not getting …
    Wat to do?

    Any one can give suggestion for this?…


    Thanks & Regards
    tulasi

  6. August 3, 2012 at 11:03 am

    What do you mean by “not working”?
    Let me assume that you mean that when you disable the internet the function is not triggered.

    In this case make sure you don’t disable the internet from your computer. Disabling the internet connection on your computer won’t reflect changes on the emulator.

    You will need to disable the internet directly from the emulator like you would do on a real phone:

    Settings -> Wireless and networks -> Mobile Networks -> Use packed data.

    (I suppose the path may vary from emulator to emulator depending of SDK version)

  7. May 8, 2013 at 2:56 pm

    Thanks for this tutorial!

    Is just what I needed for my project.

    Cheers!

  8. Meghna
    July 6, 2013 at 6:30 pm

    Thanks for the nice tutorial man… Even this
    http://www.compiletimeerror.com/2013/06/check-internet-connection-in-android.html might help, have a look…

  9. Lotes Molapo
    October 9, 2013 at 11:44 am

    keep up the good work. thanks for the posts and tutorials

  1. No trackbacks yet.

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

Follow

Get every new post delivered to your Inbox.

Join 510 other followers

%d bloggers like this: