Android Internet连接检查更好的方法 [英] Android Internet connectivity check better method
问题描述
根据Android开发者网站, 确定并监视连接状态 ,我们可以检查互联网是否处于活动状态.但是,即使仅连接了Wi-Fi且没有Internet(通知有Internet连接),此方法也无法正常工作.
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).
现在,我对网站进行ping操作,并检查Internet连接是否可用.而且此方法需要更多的处理时间.有没有比这更好的方法来检查Internet连接,从而避免ping地址的时间延迟?
Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?
推荐答案
尝试一下:
这真的很简单而且快捷:
It's really simple and fast:
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) { return false; }
}
然后在任何要检查的地方都使用此:
Then wherever you want to check just use this:
if (isInternetAvailable("8.8.8.8", 53, 1000)) {
// Internet available, do something
} else {
// Internet not available
}
这篇关于Android Internet连接检查更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!