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:
As usual in Android you do not create the
ConnectivityManager yourself, but ask the
Context-object to give you one:
ConnectivityManager connManager =
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();
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.
Without explicit permission you are not allowed to check the network state. Thus you also have to add the following line to your
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />