I'm working on an Android projet and I need to know when the user have access to internet. (not just if the wifi is activated. For example in case where the user used a hotspot wifi connection)
I use this method :
public static boolean isOnline(final Context context) {
boolean result = false;
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).isConnectedOrConnecting() || connec.getNetworkInfo(1).isConnectedOrConnecting()) {
URL url = new URL("https://www.google.fr");
URLConnection urlConnection;
urlConnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
int responseCode = httpConnection.getResponseCode();
result = (responseCode == 200);
}
return result;
}
This method works but slows down my application because it's use in a Timer which checks the connection of the user each 5 seconds. And I need to know in real time the connection state of the user...
Somebody know an other way to verify the internet connection ? Maybe with java reflection...?