Wednesday, June 2, 2010

Checking Network Availability

I have seen a few applications which first try to initiate a network connection before checking if any network is available or not. And then, if the request fails, they toast a message saying "No network available". This might not be the right approach in most of the situations. Before initiating a connection, we should always check the availability of a network and then proceed. Android provides a simple way by which you can know the status of the active network if any. So, why not use it. It's very simple.

The code:
 public static boolean isNetworkAvailable(Context context) {
            boolean value = false;
            ConnectivityManager manager = (ConnectivityManager) context
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                           value = true;
            return value;