我知道这个问题已经被问了几次,例如在这里和这里,但我真的还没有做类似的东西得到想要的结果这个用于网络连接时检查
当我连接到当前没有互联网连接的Wi-Fi路由器时,来自网络信息的isAvailable()和isConnected()方法都会给出布尔值的结果.
是否确保电话/应用程序实际连接到互联网的唯一方法是实际轮询/ ping资源以检查连接或在尝试发出请求时处理异常?
正如@Levit所述,显示了两种检查网络连接/互联网访问的方式
-- 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;
}
Run Code Online (Sandbox Code Playgroud)
-- 连接到 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; }
}
Run Code Online (Sandbox Code Playgroud)
第二种方法非常快(无论哪种方式),适用于所有设备,非常可靠。但不能在UI线程上运行。