我有此常用代码来向服务器发出HTTP请求。

      HttpClient httpclient = new DefaultHttpClient();
      ...
        HttpGet httpGet = new HttpGet(finalUri.toURI());
        httpGet.addHeader("Accept", "text/xml");

        response = httpclient.execute(httpGet);


有互联网连接时,此方法工作正常。但是,当没有Internet连接时,代码只需在httpclient.execute(httpGet);处等待很长时间,直到它超时并引发异常并使应用程序崩溃。

01-10 15:17:48.612  20692-20806/com.somepackage.somepackage  E/EXCEPTION﹕ Unable to resolve host "myapi.myhost.com": No address associated with hostname


作为例外,我可以捕获UnknownHostException e并对其进行处理。但是仍然有办法预先知道互联网连接丢失了吗?

最佳答案

您可以为此目的使用NetworkInfo。

private boolean checkNetworkConnection() {
    NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isConnected()) {
        return false;
    } else {
        return true;
    }
}

10-07 13:07