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.

11 thoughts on “Android – Detecting Internet Connection

  1. 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?

  2. 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

  3. 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)

  4. What should I write after this to open your RSS Feed app…..

    else {
    //Internet available. Do what’s required when internet is available.
    }

    Plaese help me…..

  5. Hi,
    I have Tried for my app its work but Problem is i am getting access after only on the WIFi and Mobile data but Connection is not working then also i am get
    ting access how can i resolve……!!!

Leave a comment