0

这是我的代码,但它不能正常工作,即使禁用互联网连接,它也总是返回 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
4

3 回答 3

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" />
于 2013-08-15T05:22:34.623 回答
0

你必须看看这行代码是做什么的

  NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

因为以上两个条件都很好,尝试删除上面提到的代码我认为它会起作用..

于 2013-08-15T05:23:21.953 回答
0

如果您只对连接任何类型的网络感兴趣,则不需要额外的代码:

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();

    return (ni != null) && ni.isConnected();
于 2013-08-15T05:24:45.903 回答