Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check internet connectivity in android?

Tags:

android

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?

like image 875
UMAR-MOBITSOLUTIONS Avatar asked Dec 16 '22 23:12

UMAR-MOBITSOLUTIONS


1 Answers

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;
}
like image 55
Pentium10 Avatar answered Dec 27 '22 06:12

Pentium10