El siguiente código estoy probando pero el tiempo de respuesta no es tan bueno
public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
public CheckInternetAsyncTask(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
Boolean conexion = false;
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("https://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000);
urlc.connect();
if(urlc.getResponseCode() == 200){
conexion = true;
}
} catch (IOException e) {
Log.e("TAG", "Error sin conexión", e);
conexion = false;
}
} else {
Log.d("TAG", "Red no disponible");
conexion = false;
}
return conexion;
}
}
}