I tried to check Internet connectivity with the following code snippet:
private static boolean done;
public static boolean isInternetConnected(Context context) {
boolean networkConnected = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
networkConnected = true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
networkConnected = true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
networkConnected = true;
}
if(networkConnected) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
done = (urlc.getResponseCode() == 200);
//1st
Log.d(TAG, "done =" + done);
} catch (Exception e) {
Log.e(TAG, "Error checking internet connection", e);
}
}
});
thread.start();
//2nd
Log.d(TAG, "after start done =" + done);
return done;
}
return networkConnected;
}
The problem is that "done" inside the thread "//1st" is "true: but after the thread "//2nd" is "false". I do not know what is wrong in here? can somebody explain this weird behavior?