![](/img/trans.png)
[英]How to detect WIFI is connected, but no internet (data limit is over / no signal)
[英]How to detect when WIFI is connected to internet?
我正在构建一个 Android 应用程序,我使用下面的代码来检测是否有网络连接。 它运行良好,可以检测移动和 WIFI 网络。
我的问题是如何检测实际的互联网连接。 下面的代码在连接到 WIFI 时返回 true,但 WIFI 可能不一定连接到 Internet。
代码
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
谢谢你的时间。
梅尔
您应该尝试访问互联网地址。 因此,您应该检查 InetAdress 类和方法 isReachable: http : //developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29
这段代码会检查你的设备是否有网络连接,如果信号不好它会显示一个 Toast 否则不会,
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if(Info == null){
Toast.makeText(RegisterActivity.this,"Network Connection Failed! ", Toast.LENGTH_SHORT).show();
}
你应该试试这个:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)
m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() ==
NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
并且只检查 wifi 更简单:
private boolean isWifiConnected() {
int WIFI_STATE = wifi.getWifiState();
if(WIFI_STATE == WifiManager.WIFI_STATE_ENABLED)
return true;
return false;
}
此代码将真正测试互联网连接:
public static boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("google.com");
return address.isReachable(2000); //This really tests if the ip, given by the url, is reachable
//return !address.equals(""); //This just tests if the IP is available but it could be taken in a previous request when internet was available
} catch (Exception e) {
Log.d("Internet check", "Unable to reach the url: "+url);
}
return false;
}
您可以尝试 ping http://google.com或执行类似操作以确认可以访问 Internet。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.