Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Internet Connection Android

Wish I could do a test to verify internet connection, I don't want check network state, because it only detects if I have activated internet on my device, y yo quiero revisar si es posible conectarse a internet. Something like a ping.

like image 311
Loreln Avatar asked May 15 '13 21:05

Loreln


2 Answers

Try following:

public boolean checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

dont forget the access

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

else

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }
like image 188
Oli Avatar answered Nov 15 '22 04:11

Oli


It does works for me:

To verify network availability:

private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

To verify internet access:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}
like image 22
Musculaa Avatar answered Nov 15 '22 03:11

Musculaa