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:
- 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(); }
- 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 returnnull
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 invokingisConnectedOrConnecting()
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 returnstrue
only if the network is already connected. This can be achieved by replacingisConnectedOrConnecting()
method withisConnected()
. See the Android SDK for more details about the method.