Quantcast
Channel: Thiranjith's Blog » Android
Viewing all articles
Browse latest Browse all 10

How to check network connectivity in Android

$
0
0

This tutorial shows how to check whether your Android phone is currently connected to a network or not (e.g. Wi-Fi, 3G etc.).

A while back, I wrote a tutorial on how to dynamically monitor network connectivity in Android. However, sometimes all you want is to check if your phone has an active network connection at any given time (i.e. not to constantly monitor its status).

The simplest way to check network connectivity at any given point in time is to:

  1. Create a utility function to check network status as shown below
    public static boolean isOnline(Context context) {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

  2. Add the following permission to the Android Manifest in order to monitor current network state
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Explaining the utility function

There are several key discussion points above the isOnline(Context) utility function I described earlier:

  • ConnectivityManager#getActiveNetworkInfo() method can return null if the phone is either in Airplane mode or all network interfaces are turned off manually. Therefore, we need to do the null check (activeNetwork != null) before invoking isConnectedOrConnecting() method.
  • isConnectedOrConnecting() method checks for networks that are in the process of being connected. Depending on the requirements, you might want to use a more strict version where the method returns true only if the network is already connected. This can be achieved by replacing isConnectedOrConnecting() method with isConnected(). See the Android SDK for more details about the method.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images