如何检查我的应用程序中的3G状态:

时间:2011-09-22 08:28:54

标签: android

实际上我使用了以下代码来检查wifi是否处于活动状态(工作正常)。 我只想确认我是否可以使用相同的代码来检查3G活动状态:

 public boolean checkwifi()
    {
        ConnectivityManager connec = (ConnectivityManager) this.getSystemService(this.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;
    }

2 个答案:

答案 0 :(得分:0)

是的 - 此代码应该有效。我有一些你可能想要实现的功能:

public static boolean isOnline(Context context) {
    //ConnectivityManager is used to check available network(s)
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null;
}

这与您的代码相同 - 它会告诉您是否通过任何方法(3G或WiFi)在线,但它更简洁。

**编辑**

以下是该方法的来源 - 如果没有活动的网络连接,它将返回null,或者将返回当前连接的NetworkInfo对象:

/**
 * Return NetworkInfo for the active (i.e., connected) network interface.
 * It is assumed that at most one network is active at a time. If more
 * than one is active, it is indeterminate which will be returned.
 * @return the info for the active network, or {@code null} if none is active
 */
public NetworkInfo getActiveNetworkInfo() {
    enforceAccessPermission();
    for (NetworkStateTracker t : mNetTrackers) {
        NetworkInfo info = t.getNetworkInfo();
        if (info.isConnected()) {
            return info;
        }
    }
    return null;
}

答案 1 :(得分:0)

检查您的连接(WIFI或移动设备)是开还是关,试试这个:

boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING ||
           connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
        //we are connected to a network

        connected = true;
    }
    else
        connected = false;