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