Izzo32
Izzo32

Reputation: 179

Check Internet Connection in Android (Not connection State)

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

Upvotes: 0

Views: 178

Answers (1)

mapodev
mapodev

Reputation: 988

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

Upvotes: 1

Related Questions