Alireza.pir Alireza.pir - 11 days ago 7
Android Question

Android - Check Internet Access

I have read this Answer About Getting Internet Connection Status in Android:

http://stackoverflow.com/a/22256277/4225644

But It doesn't work properly, for example if i have a network connection with no internet Access, this method takes too long time to return False:

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;
}


How Can I decrease this Time to have a faster answer?

Answer

Use this code :

public static boolean isInternetConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();

    if (ni == null)
        return false;
    else {
        if (ni.isConnected())
            if (isOnline(context))
                return true;
            else
                return false;
        return false;
    }
}


public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url
                    .openConnection();
            urlc.setConnectTimeout(2000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}