views:

56

answers:

1

I have an IntentService which makes some web service calls. Before making these calls I check to make sure the device has network connectivity. I am doing so like this:

 private boolean isOnline() {
  ConnectivityManager connec =  (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
  return connec.getNetworkInfo(0).isConnectedOrConnecting();
 }

Unfortunately, when I'm debugging on my Android device, this returns false when I have both a network and a wireless connection.

Some interesting tidbits about connec.getNetworkInfo(0):

mIsAvailable = true
mNetworkType = 0
mTypeName = "mobile"
mState.name = "DISCONNECTED"

Clearly this code is not sufficient (perhaps it would only return true if I sent some bit over the network and turned the radio on?). Moreover, since I'm not well versed in the ConnectivityManager, I'm assuming I should probably be scanning all networks (ie: getNetworkInfo(0 through N)).

How can I properly accomplish what I'm wanting here?

+2  A: 

Try this:

public static boolean isNetworkConnected(Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = cm.getActiveNetworkInfo();

    if(network != null){
        return network.isAvailable();
    }

    return false;
}
danh32
Ya this will work. I found this, but had not updated this post yet. Thank you
Andrew