0

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

}

I.Ardel
  • 79
  • 2
  • 13
  • You need to join your thread back to the main thread when it finishes and then return the connection status. Right now you return before the thread finishes its work so it will be false – Halfpint Apr 08 '17 at 20:57
  • btw `isNetworkAvailable` is the right way to do it. `hasInternetAccess` is an absolute horrible way to do it. It returns false when there is a network connection but http://clients3.google.com/ is down. – Veneet Reddy Apr 08 '17 at 20:57

0 Answers0