Android: Checking Connectivity

Whenever your app needs to access the internet, you should be sure that it can do so. To find more about the state of the connectivity, Android provides two classes that help you with this task: ConnectivityManager and NetworkInfo.

As usual in Android you do not create the ConnectivityManager yourself, but ask the Context-object to give you one:

ConnectivityManager connManager =
   (ConnectivityManager)context.
   getSystemService(Context.CONNECTIVITY_SERVICE);

The the manager in itself is not useful. But it offers access to the NetworkInfo object that you can use. There are three ways to get NetworkInfo-objects – but if you want to know whether you are connected right now, the following works best:

NetworkInfo info = connManager.getActiveNetworkInfo();

Alternatively you can use the ConnectionManager to get an array of all available NetworkInfo objects on the system. Each of these objects represents the information for one type of network (e.g. WIFI).

NetworkInfo info = connManager.getAllNetworkInfo();

With a NetworkInfo object you can then find out all you need to know. You can check if a certain type of connectivity is available, if you are connected and of what quality your connection is.

The next code sample shows the most important methods of NetworkInfo. The screens below show you the results for being not connected at all or being connected via WIFI or UMTS respectively.

info.isAvailable()
info.isConnected()
info.isConnectedOrConnecting()
info.getState()
info.getDetailedState()
info.getTypeName()
info.getType()
info.getSubtypeName()
info.getSubtype()

NetworkInfo showing only disconnected states

NetworkInfo showing only disconnected states


NetworkInfo showing an established WIFI connection

NetworkInfo showing an established WIFI connection


NetworkInfo showing an established UMTS connection

NetworkInfo showing an established UMTS connection

Without explicit permission you are not allowed to check the network state. Thus you also have to add the following line to your AndroidManifest.xml:

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

Share this article:

You can leave a response, or trackback from your own site.

One Response to “Android: Checking Connectivity”

  1. I have a need to disable network state in one of my apps. Do you know of a way to disable network and then enable at a later time? I was using AirplaneMode to accomplish this but with the roll out of Android 4.2 this is no longer feasible.

    Thanks!

    Marty

Leave a Reply

You can also subscribe without commenting.

Subscribe to RSS Feed My G+-Profile Follow me on Twitter!