Question

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?

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top