如何检查无线或3G网络是否在安卓设备上可用

2022-09-01 10:40:39

在这里,我的Android设备同时支持wifi和3G。在此设备上的特定时间哪个网络可用。因为我的要求是当3g可用时,我必须上传少量数据。当wifi可用时,整个数据必须上传。所以,我必须检查连接是wifi还是3g。请帮帮我。提前致谢。


答案 1

我用这个:

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return false;
    }
    return true;
}

您还需要

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在 AndroidMainfest 中.xml

要获取网络类型,您可以使用以下代码段:

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
State mobile = conMan.getNetworkInfo(0).getState();

//wifi
State wifi = conMan.getNetworkInfo(1).getState();

然后像这样使用它:

if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
    //mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
    //wifi
}

要获得移动网络的类型,我会尝试TelephonyManager#getNetworkTypeNetworkInfo#getSubtypeName。


答案 2

您需要在Android清单文件中添加以下权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

之后,您可以使用以下功能检查wifi或移动网络是否已连接

public static boolean isWifiConnected(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return ((netInfo != null) && netInfo.isConnected());
    }

public static boolean isMobileConnected(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return ((netInfo != null) && netInfo.isConnected());
    }

developer.android.com 的一些参考资料是:

  1. https://developer.android.com/reference/android/net/ConnectivityManager.html
  2. https://developer.android.com/reference/android/net/NetworkInfo.html
  3. https://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo()

推荐