这是我的代码,但它无法正常工作,即使禁用互联网连接也始终返回true:
public boolean hasConnection(Context context) {
/**
*context.getsystemservice parameters:
name: The name of the desired service.
Returns: The service or null if the name does not exist.
*/
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}//end of hasConnection class
答案 0 :(得分:0)
使用此代码
public boolean CheckInternet()
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Here if condition check for wifi and mobile network is available or not.
// If anyone of them is available or connected then it will return true, otherwise false;
if (wifi.isConnected()) {
return true;
} else if (mobile.isConnected()) {
return true;
}
return false;
}
许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:0)
你必须看看这行代码是做什么的
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
因为以上两个条件都没问题并且尝试删除上面提到的代码我认为它会起作用..
答案 2 :(得分:0)
如果您只对任何类型的网络连接感兴趣,则不需要额外的代码:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null) && ni.isConnected();