你说的对。您提供的代码仅检查是否存在网络连接。检查是否存在活动 Internet 连接的最佳方法是尝试通过 http 连接到已知服务器。
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
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();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
当然,您可以将http://www.google.com
URL 替换为您想要连接的任何其他服务器,或者您知道正常运行时间较长的服务器。
正如 Tony Cho 在下面的评论中指出的那样,请确保您不要在主线程上运行此代码,否则您将收到 NetworkOnMainThread 异常(在 Android 3.0 或更高版本中)。请改用 AsyncTask 或 Runnable。
如果你想使用 google.com 你应该看看 Jeshurun 的修改。在他的回答中,他修改了我的代码并使其更有效率。如果您连接到
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
然后检查 204 的响应代码
return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
那么您不必先获取整个谷歌主页。