0

I am developing an app in which I need to check if an internet connection is available or not. The code I have written seems to handle all cases but it is not working in my emulator. My code:

public boolean hasConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo wifiNetwork = cm
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected()) {
            return true;
        }

        NetworkInfo mobileNetwork = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected()) {
            return true;
        }

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            return true;
        }
        return false;
    }

The problem is that it is never returning false whether the internet connection is available or not, both in a device and in my emulator. But it is working well if the device is connected with wifi connection. What problem with that snippet?

andyg0808
  • 1,367
  • 8
  • 18
Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • Try http://stackoverflow.com/questions/17717749/check-for-active-internet-connection-android – Shobhit Puri Aug 17 '13 at 04:41
  • What you mean by it never return false and working well if device connected with wifi? If it never return false then how can it work well with wifi ? – Vipul Purohit Aug 17 '13 at 05:22

1 Answers1

-1

Try this method.

private boolean IsNetworkAvailable() {
    ConnectivityManager mConnectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mActiveNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    return mActiveNetworkInfo != null && mActiveNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
SilentKiller
  • 6,944
  • 6
  • 40
  • 75