【发布时间】:2017-01-11 06:24:04
【问题描述】:
我一直在寻找一种快速有效的方法来检查互联网连接,我发现最好 ping google 来查找互联网连接状态。但是我找到了许多 ping google 的方法,我很困惑哪一种在所有这些中使用。以下是我看到的方法。
方法一:
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
方法二:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
方法三:
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
方法四:
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;
}
我应该选择哪一个?我需要一种更快更有效的方法。
【问题讨论】:
-
我会说方法 1,因为这将绕过对功能性 DNS 服务器的需求。不过,方法 1 和 2 并没有那么大的不同。
-
@cricket_007,我的方法是否会在应用程序上产生复杂性检查连接?
-
@W4R10CK 它检查网络连接,不一定是互联网可达性
标签: android internet-connection android-internet