0

I need help to check if there's a connection to some given URL to make sure i have a connection to the internet.

I've used this code:

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

but it's not so helpful, cause the device may be connected to WiFi or Mobile network but there's no connection to the internet.

Please help

Izzo32
  • 179
  • 1
  • 4
  • 16

1 Answers1

1

You can ping a website for checking if Internet is available. You can ping google.com, mostly online.

public static boolean ping(String url, int timeout) {
    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

taken from here Preferred Java way to ping an HTTP URL for availability

Community
  • 1
  • 1
mapodev
  • 988
  • 8
  • 14
  • yup yup it works now, i used to put "http://www.google.com" in the url string, but i changed it to "google.com" and it works great now. Thanks a lot – Izzo32 Jun 27 '14 at 16:27
  • I figured now that it always returns false!, why so?! – Izzo32 Jun 27 '14 at 16:40