[英]Check Internet connectivity - Android
I know this question has been asked a couple of times, example here and here but I`m still not getting the desired results by doing something similar to this when checking for network connectivity 我知道这个问题已经被问了几次,例如在这里和这里 ,但我真的还没有做类似的东西得到想要的结果这个用于网络连接时检查
The isAvailable() and isConnected() methods from Network Info both give a result of boolean true when i`m connected to a Wi-Fi router which currently has no internet connectivity . 当我连接到当前没有互联网连接的Wi-Fi路由器时,来自网络信息的isAvailable()和isConnected()方法都会给出布尔值的结果。
Here is a screenshot of my phone which can detect the situation in hand. 这是我的手机的屏幕截图,可以检测到手头的情况。
Is the only way to make sure that the phone/application is actually connected to the internet is actually poll/ping a resource to check for connectivity or handle an exception when trying to make a request? 是否确保电话/应用程序实际连接到互联网的唯一方法是实际轮询/ ping资源以检查连接或在尝试发出请求时处理异常?
As stated by @Levit, Showing two way of checking Network connection / Internet access 正如@Levit所述,显示两种方式检查网络连接/ Internet访问
-- Ping a Server - Ping服务器
// ICMP
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 (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
-- Connect to a Socket on the Internet (advanced) - 连接到Internet上的套接字(高级)
// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; }
}
second method very fast (either way), works on all devices, very reliable. 第二种方法非常快(无论哪种方式),适用于所有设备,非常可靠。 But can't run on the UI thread.
但无法在UI线程上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.