Android NetworkState问题,返回两次

时间:2014-12-12 22:08:27

标签: android if-statement android-wifi connectivity network-state

我有下面的代码,用于检查所使用的网络是Cell还是WiFi。如果WiFi然后返回字符串WiFi,如果单元格返回字符串Cell。我的代码是:

private String checkNetworkState() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    //  NetworkInfo mEthernet = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (mWifi!=null) isOnWifi = mWifi.isConnected();
        if (m3G!=null) is3G = m3G.isConnected();

        if(isOnWifi == true) {
            return "WiFi";
        }
        else {
            return "Cell";
        }

    }

我已启用WiFi调试。 isOnWifi是真的,is3G是假的。但是,if和else都被调用了,为什么会这样呢?

说过我得到的返回字符串实际上是" WiFi",而不是Cell。这通常吗?

1 个答案:

答案 0 :(得分:0)

如果您正在检查网络状态,则必须更改方法,

private boolean checkNetworkState() {
    ConnectivityManager connManager = (ConnectivityManager)  getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (mWifi!=null) isOnWifi = mWifi.isConnected();
    if (m3G!=null) is3G = m3G.isConnected();

    if(isOnWifi == true || is3G == true) {
        return true;
    }

    return false;
}

您无法从同一方法获得两个值,请尝试对每种情况使用相应的方法:

public boolean isConnectedWifi() {
         ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
         NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
         return mWifi.isConnected();
}

public boolean isConnectedMobile() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
         NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
         return m3G.isConnected();
}