Detect network connection type on Android

前端 未结 14 1320
后悔当初
后悔当初 2020-11-22 05:55

How do you detect the network connection type on Android?

Is it through ConnectivityManager.getActiveNetworkInfo().getType(), and is the answer limited

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:31

    You can use getSubtype() for more details. Check out slide 9 here: http://dl.google.com/io/2009/pres/W_0300_CodingforLife-BatteryLifeThatIs.pdf

    ConnectivityManager mConnectivity = null;
    TelephonyManager mTelephony = null;
    // Skip if no connection, or background data disabled
    NetworkInfo info = mConnectivity.getActiveNetworkInfo();
    if (info == null || !mConnectivity.getBackgroundDataSetting()) {
        return false;
    }
    
    // Only update if WiFi or 3G is connected and not roaming
    int netType = info.getType();
    int netSubtype = info.getSubtype();
    if (netType == ConnectivityManager.TYPE_WIFI) {
        return info.isConnected();
    } else if (netType == ConnectivityManager.TYPE_MOBILE
        && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
        && !mTelephony.isNetworkRoaming()) {
            return info.isConnected();
    } else {
        return false;
    }
    

    Also, please check out Emil's answer for a more detailed dive into this.

提交回复
热议问题