0

I would like to check if the android app has an internet connection available. I tried this could, which is not working due to the Googles requirement of https.

private static boolean netIsAvailable() {
    try {
        final URL url = new URL("http://www.google.com");
        final URLConnection conn = url.openConnection();
        conn.connect();
        conn.getInputStream().close();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.d(TAG, e.toString());
        return false;
    }

I am getting the error: java.io.IOException: Cleartext HTTP traffic to www.google.com not permitted

Which other ways there are?

Ludwigm
  • 23
  • 7
  • 2
    Does this answer your question? [Detect whether there is an Internet connection available on Android](https://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android) – Jason Mar 02 '20 at 15:19
  • @Jason Please don't copy paste code from that link as all top answers contain code that's deprecated. – Zun Mar 02 '20 at 15:25

1 Answers1

1

Using https://developer.android.com/reference/android/net/ConnectivityManager is an option:

Something like:

 NetworkCapabilities networkCapabilities = mConnectivityService.getNetworkCapabilities(mConnectivityService.getActiveNetwork());
                if (networkCapabilities != null) {
                    if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {

                        // do something with internet
                    } else {
                        // no internet
                    }
                } else {
                    // no internet
                }

Although, is there a reason why you cannot just use https in your URL?

Thomas__
  • 320
  • 3
  • 13
  • just use https will lead to `android.os.NetworkOnMainThreadException` – Ludwigm Mar 02 '20 at 16:37
  • what ist `mConnectivityService` ? – Ludwigm Mar 02 '20 at 16:39
  • That is because you're trying to do the request on main thread, do it as an `AsyncTask` or similar – Thomas__ Mar 02 '20 at 16:39
  • `mConnectivityService` is `ConnectivityManager`; `mConnectivityService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);` – Thomas__ Mar 02 '20 at 16:40
  • This seems to be working: private boolean netIsAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } – Ludwigm Mar 03 '20 at 18:40
  • Similar to what I've used in the past! – Thomas__ Mar 03 '20 at 19:36