Detect network connection type on Android

前端 未结 14 1106
后悔当初
后悔当初 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.

    0 讨论(0)
  • 2020-11-22 06:31

    You can check like this

    public void checktype() {
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) { // connected to the internet
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                Toast.makeText(this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                Toast.makeText(this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:34

    Shown below different ways to do that. Please, note that there are a lot of network types in ConnectivityManager class. Also, if API >= 21, you can check the network types in NetworkCapabilities class.

        ConnectivityMonitor connectivityMonitor = ConnectivityMonitor.getInstance(this);
        boolean isWiFiConnected = connectivityMonitor.isWifiConnection();
        boolean isMobileConnected = connectivityMonitor.isConnected(ConnectivityManager.TYPE_MOBILE);
        Log.e(TAG, "onCreate: isWiFiConnected " + isWiFiConnected);
        Log.e(TAG, "onCreate: isMobileConnected " + isMobileConnected);
        ConnectivityMonitor.Listener connectivityListener = new ConnectivityMonitor.Listener() {
            @Override
            public void onConnectivityChanged(boolean connected, @Nullable NetworkInfo networkInfo) {
                Log.e(TAG, "onConnectivityChanged: connected " + connected);
                Log.e(TAG, "onConnectivityChanged: networkInfo " + networkInfo);
                if (networkInfo != null) {
                    boolean isWiFiConnected = networkInfo.getType() == NetworkCapabilities.TRANSPORT_WIFI;
                    boolean isMobileConnected = networkInfo.getType() == NetworkCapabilities.TRANSPORT_CELLULAR;
                    Log.e(TAG, "onConnectivityChanged: isWiFiConnected " + isWiFiConnected);
                    Log.e(TAG, "onConnectivityChanged: isMobileConnected " + isMobileConnected);
                }
            }
        };
        connectivityMonitor.addListener(connectivityListener);
    
    0 讨论(0)
  • 2020-11-22 06:36

    To get a more precise (and user friendly) information about connection type. You can use this code (derived from a @hide method in TelephonyManager.java).

    This method returns a String describing the current connection type.
    i.e. one of : "WIFI" , "2G" , "3G" , "4G" , "5G" , "-" (not connected) or "?" (unknown)

    Remark: This code requires API 25+, but you can easily support older versions by using int instead of const. (See comments in code).

    public static String getNetworkClass(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);      
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null || !info.isConnected())
            return "-"; // not connected
        if (info.getType() == ConnectivityManager.TYPE_WIFI)
            return "WIFI";
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            int networkType = info.getSubtype();
            switch (networkType) {
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                case TelephonyManager.NETWORK_TYPE_CDMA:
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                case TelephonyManager.NETWORK_TYPE_IDEN:     // api< 8: replace by 11
                case TelephonyManager.NETWORK_TYPE_GSM:      // api<25: replace by 16
                    return "2G";
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                case TelephonyManager.NETWORK_TYPE_HSPA:
                case TelephonyManager.NETWORK_TYPE_EVDO_B:   // api< 9: replace by 12
                case TelephonyManager.NETWORK_TYPE_EHRPD:    // api<11: replace by 14
                case TelephonyManager.NETWORK_TYPE_HSPAP:    // api<13: replace by 15
                case TelephonyManager.NETWORK_TYPE_TD_SCDMA: // api<25: replace by 17
                    return "3G";
                case TelephonyManager.NETWORK_TYPE_LTE:      // api<11: replace by 13
                case TelephonyManager.NETWORK_TYPE_IWLAN:    // api<25: replace by 18
                case 19: // LTE_CA
                    return "4G";
                case TelephonyManager.NETWORK_TYPE_NR:       // api<29: replace by 20
                    return "5G";
                default:
                    return "?";
             }
        }
        return "?";
    }
    
    0 讨论(0)
  • 2020-11-22 06:40

    On top of Emil's awsome answer I'd like to add one more method, for checking if you actually have Internet access as you could have data set to off on your phone.

    public static boolean hasInternetAccess(Context c){
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        if(isConnected(c) && tm.getDataState() == TelephonyManager.DATA_CONNECTED)
           return true;
        else
            return false;
    }
    

    Note that this is only for checking if theres a cellular data connection and will return false if you have WiFi connected, as the cellular data is off when WiFi is connected.

    0 讨论(0)
  • 2020-11-22 06:41

    I use this simple code:

    fun getConnectionInfo(): ConnectionInfo {
        val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
        return if (cm.activeNetwork == null) {
            ConnectionInfo.NO_CONNECTION
        } else {
            if (cm.isActiveNetworkMetered) {
                ConnectionInfo.MOBILE
            } else {
                ConnectionInfo.WI_FI
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题