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.

Based on conducted researches, I found that the class responsable for querying the state of network connectivity is the ConnectivityManager. The primary responsibilities of this class are to:

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

We can get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE);

Important: Before proceeding to check the internet connection, the ACCESS_NETWORK_STATE permission must be set in the AndroidManifest file, otherwise you’ll get a security exception:

1. android.permission.ACCESS_NETWORK_STATE”

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

The code for checking the internet connection looks like this:

1 ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
2 NetworkInfo ni = cm.getActiveNetworkInfo();
3
4 if (ni!=null && ni.isConnected())
5 Log.d(“GREC”, “connected”);
6 else
7 Log.d(“GREC”, “not connected”);

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.

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.

For more information about ConnectivityManager and in general the work with network, consider this link: http://developer.android.com/reference/android/net/ConnectivityManager.html

Tags

Filed Under: Android

Anthony Gee About the Author: Anthony G. is an IT specialist with more than 9 years of solid working experience in the Web Hosting industry. Currently works as server support administrator, involved in consultative discussions about Web Hosting and server administration. One of the first writers in the Onlinehowto.net website, now writing for Free Tutorials community - he is publishing tutorials and articles for the wide public, as well as specific technical solutions.

Leave a Reply