Friday, September 3, 2010

Check Android network connection sample code

Chances are if you're building an Android app, you're going to be using the device's data connection. After all, the beauty of these things is having the power of the internet at your fingertips. You have to be careful though when building apps to always for the existence of an active connection. Failure to do so and then trying to fetch data could result in a negative user experience or possibly even crash.

Luckily, there's an easy way to check for data connections prior to making calls so you can either proceed or handle gracefully. The sample class below provides everything you need. Just insert into your project and call when necessary...



public class Networking {
 /*
 *@return boolean return true if the application can access the internet
 */
 public static boolean isNetworkAvailable(Context context) {
     ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
     if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
           for (int i = 0; i < info.length; i++) {
              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                 return true;
              }
           }
        }
     }
     return false;
  }
}

6 comments:

  1. Thanks for valuable information.

    ReplyDelete
  2. this is great.This was really helpful in my project.
    However I wish to know if there is anyway to modify this code so that only selected applications can access the internet through 3G while other applications that are not selected will not be able to use 3G data connection.
    This is the last part of my project and I have been looking for a solution and I have not found any. only this was the closest thing to a solution.
    I hope to get your opinion on my problem.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Remember to add:

    android.permission.ACCESS_NETWORK_STATE

    to AndroidManifest.xml

    ReplyDelete