0

I'm using this code to check if the network is connected or not. it is working perfectly on all Android versions up to 8.1 but since Android Pie, it always shows that I'm not connected!

private boolean isNetworkAvailable() {
        final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo == null || !networkInfo.isConnected()) {
            onUpdateNetworkStatus(false);
            return false;
        }

        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final URL url = new URL("http://clients3.google.com/generate_204");
                    final HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestProperty("User-Agent", "Android");
                    httpURLConnection.setRequestProperty("Connection", "close");
                    httpURLConnection.setConnectTimeout(1500);
                    httpURLConnection.connect();
                    onUpdateNetworkStatus(httpURLConnection.getResponseCode() == 204 && httpURLConnection.getContentLength() == 0);
                } catch (Exception e) {
                    onUpdateNetworkStatus(false);
                }
            }
        });

        thread.start();

        return true;
    }
jins joseph
  • 271
  • 1
  • 11
issamabuaqlien
  • 58
  • 1
  • 10

1 Answers1

0

I will recommend to use one of the following libraries to make network checking process easier in your Apps

  1. merlin
  2. Android Network Manager
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36