I try to write class that check if device is connected to internet, but I have a problem: in thread of hasInternetAccess() method I get connection = true, but hasInternetAccess() return false. I think that hasInternetAccess() reutrn false before thread get correct connection status, but how I can fix it?
public class ConnectivityStatus {
private Context mContext;
private boolean connection = false;
public ConnectivityStatus(Context mContext) {
this.mContext = mContext;
}
public boolean hasInternetAccess() {
if (isNetworkAvailable()) {
new Thread() {
@Override
public void run() {
try {
HttpURLConnection url = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
url.setRequestProperty("User-Agent", "Android");
url.setRequestProperty("Connection", "close");
url.setConnectTimeout(2000);
url.connect();
if (url.getResponseCode() == 204 && url.getContentLength() == 0) {
connection = true;
}
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
}
}.start();
} else {
Log.d(TAG, "No network available!");
}
return connection;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}