4

friends,

i am trying to check internetconnectivity in android and using following code

final ConnectivityManager conn_manager = (ConnectivityManager) 
            this.getSystemService(Context.CONNECTIVITY_SERVICE);


            final NetworkInfo network_info = conn_manager.getActiveNetworkInfo();
            if ( network_info != null && network_info.isConnected() ) 
            {
                return true;
            }
            else
            {
                return false;
            }

but it gives me network/ wifi connectivity if wifi is connected it gives me true and if internet is not connected then it also gives me true.

any one guide me what is the solution?

UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278

3 Answers3

12

Probably some issue with the logic you have in the if clause there.

I use this:

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return false;
    }
    return true;
}
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • How is it possible to extend this code to check Internet Connectivity in time intervals? – ChrisBenyamin Jul 24 '10 at 19:56
  • Probably a bad idea to monitor in time intervals, instead you should subscribe to the connectivity broadcast and action on it. See this related question: http://stackoverflow.com/questions/3307237/how-can-i-monitor-the-network-connection-status-in-android/3307565#3307565 – Pentium10 Jul 24 '10 at 20:01
  • I tried using this, but on a 2.1 device it reported false when connected to wifi mode while in airplane mode. – Navarr Feb 17 '12 at 23:08
0

You can use requstRouteToHost to check if you can connect to a specific IP address.

Firas Assaad
  • 25,006
  • 16
  • 61
  • 78
0

Use this nifty library: http://code.google.com/p/connectivity

You can subscribe to network status notification and get a callback when network status changes. Or, you can query directly if network is available. Very simple to use.

Ephraim
  • 2,234
  • 1
  • 21
  • 18