如何检测WIFI是否连接到互联网?
我正在构建一个 Android 应用程序,我使用下面的代码来检测是否有网络连接。它运行良好,可以检测移动网络和 WIFI 网络。
我的问题是如何检测实际的互联网连接。当连接到 WIFI 时,下面的代码返回 true,但 WIFI 不一定连接到互联网。
代码
protected boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}
else {
return false;
}
} //end checkInterneConnection method
感谢您的宝贵时间。
梅尔
I am building an Android app and I use the code below to detect whether there is a network connection. It works well and detects both mobile and WIFI networks.
My problem is how to detect an actual internet connection. The code below returns true when connected to WIFI however the WIFI might not necessarily be connected to the Internet.
The code
protected boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}
else {
return false;
}
} //end checkInterneConnection method
Thanks for your time.
Mel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该尝试访问互联网地址。因此,您应该检查 InetAdress 类和方法 isReachable: http ://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29
You should try to reach an internet adress. Therefor you should check the InetAdress class and the method isReachable: http://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29
这段代码将检查您的设备是否已连接互联网,如果信号差则会显示Toast,否则不会显示,
This piece of code will check whether your device Internet conecction, If the signal is Poor it will show a Toast other wise not,
您可以尝试 ping http://google.com 或执行类似操作来确认是否可以访问互联网。
You can try ping http://google.com or doing something like this to confirm it's ok to visit internet.
你应该尝试这个:
并且只检查 wifi 更简单:
You should try this:
And to check only wifi is simpler:
此代码将真正测试互联网连接:
This code will really test the internet connection: