检查互联网连接是否可用

时间:2017-04-08 20:51:19

标签: android multithreading httpurlconnection

我尝试写一个类来检查设备是否连接到互联网,但我有一个问题: 在 hasInternetAccess()方法的线程中,我得到 connection = true ,但 hasInternetAccess()返回false。在线程获得正确的连接状态之前,我认为 hasInternetAccess() reutrn为false,但是我如何解决它?

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

}

0 个答案:

没有答案