你是对的。您提供的代码仅检查是否存在网络连接。
检查是否有活动的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网址替换为您要连接的任何其他服务器,或者您知道的服务器的正常运行时间良好。
正如Tony Cho在this comment below指出的,确保你不在主线程上运行这个代码,否则你会得到一个NetworkOnMainThread异常(在Android 3.0或更高版本中)。使用AsyncTask或Runnable。
如果你想使用google.com,你应该看看Jeshurun的修改。在his answer他修改了我的代码,使它有点更有效率。如果您连接到
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
然后检查204的响应代码
return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
那么您不必先获取整个google主页。