Detect network connection type on Android

AndroidNetworkingWifiConnectivity

Android Problem Overview


How do you detect the network connection type on Android?

Is it through ConnectivityManager.getActiveNetworkInfo().getType(), and is the answer limited to Wifi and mobile?

Android Solutions


Solution 1 - Android

If the problem is to find whether the phone's network is connected and fast enough to meet your demands you have to handle all the network types returned by getSubType().

It took me an hour or two to research and write this class to do just exactly that, and I thought I would share it with others that might find it useful.

Here is a Gist of the class, so you can fork it and edited it.

package com.emil.android.util;
 
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
 
/**
 * Check device's network connectivity and speed 
 * @author emil http://stackoverflow.com/users/220710/emil
 *
 */
public class Connectivity {
  
	/**
	 * Get the network info
	 * @param context
	 * @return
	 */
	public static NetworkInfo getNetworkInfo(Context context){
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    return cm.getActiveNetworkInfo();
	}
	
	/**
	 * Check if there is any connectivity
	 * @param context
	 * @return
	 */
	public static boolean isConnected(Context context){
	    NetworkInfo info = Connectivity.getNetworkInfo(context);
	    return (info != null && info.isConnected());
	}
	
	/**
	 * Check if there is any connectivity to a Wifi network
	 * @param context
	 * @return
	 */
	public static boolean isConnectedWifi(Context context){
	    NetworkInfo info = Connectivity.getNetworkInfo(context);
	    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
	}
	
	/**
	 * Check if there is any connectivity to a mobile network
	 * @param context
	 * @return
	 */
	public static boolean isConnectedMobile(Context context){
	    NetworkInfo info = Connectivity.getNetworkInfo(context);
	    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
	}
	
	/**
	 * Check if there is fast connectivity
	 * @param context
	 * @return
	 */
	public static boolean isConnectedFast(Context context){
	    NetworkInfo info = Connectivity.getNetworkInfo(context);
	    return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
	}
	
	/**
	 * Check if the connection is fast
	 * @param type
	 * @param subType
	 * @return
	 */
	public static boolean isConnectionFast(int type, int subType){
		if(type==ConnectivityManager.TYPE_WIFI){
			return true;
		}else if(type==ConnectivityManager.TYPE_MOBILE){
			switch(subType){
			case TelephonyManager.NETWORK_TYPE_1xRTT:
				return false; // ~ 50-100 kbps
			case TelephonyManager.NETWORK_TYPE_CDMA:
				return false; // ~ 14-64 kbps
			case TelephonyManager.NETWORK_TYPE_EDGE:
				return false; // ~ 50-100 kbps
			case TelephonyManager.NETWORK_TYPE_EVDO_0:
				return true; // ~ 400-1000 kbps
			case TelephonyManager.NETWORK_TYPE_EVDO_A:
				return true; // ~ 600-1400 kbps
			case TelephonyManager.NETWORK_TYPE_GPRS:
				return false; // ~ 100 kbps
			case TelephonyManager.NETWORK_TYPE_HSDPA:
				return true; // ~ 2-14 Mbps
			case TelephonyManager.NETWORK_TYPE_HSPA:
				return true; // ~ 700-1700 kbps
			case TelephonyManager.NETWORK_TYPE_HSUPA:
				return true; // ~ 1-23 Mbps
			case TelephonyManager.NETWORK_TYPE_UMTS:
				return true; // ~ 400-7000 kbps
			/*
			 * Above API level 7, make sure to set android:targetSdkVersion 
			 * to appropriate level to use these
			 */
			case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
				return true; // ~ 1-2 Mbps
			case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
				return true; // ~ 5 Mbps
			case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
				return true; // ~ 10-20 Mbps
			case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
				return false; // ~25 kbps 
			case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
				return true; // ~ 10+ Mbps
			// Unknown
			case TelephonyManager.NETWORK_TYPE_UNKNOWN:
			default:
				return false;
			}
		}else{
			return false;
		}
	}
 
}

Also make sure to add this permission to you AndroidManifest.xml

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

Sources for network speeds include wikipedia & http://3gstore.com/page/78_what_is_evdo_mobile_broadband.html

Solution 2 - Android

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 "?";
}

Solution 3 - Android

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.

Solution 4 - Android

@Emil's answer above is brilliant.

Small addition: We should ideally use TelephonyManager to detect network types. So the above should instead read:

/**
 * Check if there is fast connectivity
 * @param context
 * @return
 */
public static boolean isConnectedFast(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), tm.getNetworkType()));
}

Solution 5 - Android

The answer from Emil Davtyan is good, but network types have been added that are not accounted for in his answer. So, isConnectionFast(int type, int subType) may return false when it should be true.

Here is a modified class which uses reflection to account for added network types in later APIs:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>Utility methods to check the current network connection status.</p>
 *
 * <p>This requires the caller to hold the permission
 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.</p>
 */
public class NetworkUtils {

  /** The absence of a connection type. */
  public static final int TYPE_NONE = -1;

  /** Unknown network class. */
  public static final int NETWORK_CLASS_UNKNOWN = 0;
  /** Class of broadly defined "2G" networks. */
  public static final int NETWORK_CLASS_2_G = 1;
  /** Class of broadly defined "3G" networks. */
  public static final int NETWORK_CLASS_3_G = 2;
  /** Class of broadly defined "4G" networks. */
  public static final int NETWORK_CLASS_4_G = 3;

  /**
   * Returns details about the currently active default data network. When connected, this network
   * is the default route for outgoing connections. You should always check {@link
   * NetworkInfo#isConnected()} before initiating network traffic. This may return {@code null}
   * when there is no default network.
   *
   * @return a {@link NetworkInfo} object for the current default network or {@code null} if no
   * network default network is currently active
   *
   * This method requires the call to hold the permission
   * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
   * @see ConnectivityManager#getActiveNetworkInfo()
   */
  public static NetworkInfo getInfo(Context context) {
    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
        .getActiveNetworkInfo();
  }

  /**
   * Reports the current network type.
   *
   * @return {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI} ,
   * {@link ConnectivityManager#TYPE_WIMAX}, {@link ConnectivityManager#TYPE_ETHERNET}, {@link
   * ConnectivityManager#TYPE_BLUETOOTH}, or other types defined by {@link ConnectivityManager}.
   * If there is no network connection then -1 is returned.
   * @see NetworkInfo#getType()
   */
  public static int getType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getType();
  }

  /**
   * Return a network-type-specific integer describing the subtype of the network.
   *
   * @return the network subtype
   * @see NetworkInfo#getSubtype()
   */
  public static int getSubType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getSubtype();
  }

  /** Returns the NETWORK_TYPE_xxxx for current data connection. */
  public static int getNetworkType(Context context) {
    return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
        .getNetworkType();
  }

  /** Check if there is any connectivity */
  public static boolean isConnected(Context context) {
    return getType(context) != TYPE_NONE;
  }

  /** Check if there is any connectivity to a Wifi network */
  public static boolean isWifiConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
        return true;
      default:
        return false;
    }
  }

  /** Check if there is any connectivity to a mobile network */
  public static boolean isMobileConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_MOBILE:
        return true;
      default:
        return false;
    }
  }

  /** Check if the current connection is fast. */
  public static boolean isConnectionFast(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
      case ConnectivityManager.TYPE_ETHERNET:
        return true;
      case ConnectivityManager.TYPE_MOBILE:
        int networkClass = getNetworkClass(getNetworkType(context));
        switch (networkClass) {
          case NETWORK_CLASS_UNKNOWN:
          case NETWORK_CLASS_2_G:
            return false;
          case NETWORK_CLASS_3_G:
          case NETWORK_CLASS_4_G:
            return true;
        }
      default:
        return false;
    }
  }

  private static int getNetworkClassReflect(int networkType)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Method getNetworkClass = TelephonyManager.class.getDeclaredMethod("getNetworkClass", int.class);
    if (!getNetworkClass.isAccessible()) {
      getNetworkClass.setAccessible(true);
    }
    return (int) getNetworkClass.invoke(null, networkType);
  }

  /**
   * Return general class of network type, such as "3G" or "4G". In cases where classification is
   * contentious, this method is conservative.
   */
  public static int getNetworkClass(int networkType) {
    try {
      return getNetworkClassReflect(networkType);
    } catch (Exception ignored) {
    }

    switch (networkType) {
      case TelephonyManager.NETWORK_TYPE_GPRS:
      case 16: // TelephonyManager.NETWORK_TYPE_GSM:
      case TelephonyManager.NETWORK_TYPE_EDGE:
      case TelephonyManager.NETWORK_TYPE_CDMA:
      case TelephonyManager.NETWORK_TYPE_1xRTT:
      case TelephonyManager.NETWORK_TYPE_IDEN:
        return NETWORK_CLASS_2_G;
      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:
      case TelephonyManager.NETWORK_TYPE_EHRPD:
      case TelephonyManager.NETWORK_TYPE_HSPAP:
      case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:
        return NETWORK_CLASS_3_G;
      case TelephonyManager.NETWORK_TYPE_LTE:
      case 18: // TelephonyManager.NETWORK_TYPE_IWLAN:
        return NETWORK_CLASS_4_G;
      default:
        return NETWORK_CLASS_UNKNOWN;
    }
  }

  private NetworkUtils() {
    throw new AssertionError();
  }

}

Solution 6 - Android

You can make custom Method to accomplish this task.

  public String getNetworkClass(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mTelephonyManager.getNetworkType();
        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:
                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:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "Unknown";
        }
    }

Solution 7 - Android

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.

Solution 8 - Android

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();
        }
    }
}

Solution 9 - Android

Detect the what type of network and getting the boolean value of isconnected or not use below snippet

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
public class NetworkManagerUtils {

/**
 * Get the network info
 * @param context
 * @return
 */
public static NetworkInfo getNetworkInfo(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo();
}

/**
 * Check if there is any connectivity
 * @param context
 * @return
 */
public static boolean isConnected(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected());
}

/**
 * Check if there is any connectivity to a Wifi network
 * @param context.
 * @param type
 * @return
 */
public static boolean isConnectedWifi(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}

/**
 * Check if there is any connectivity to a mobile network
 * @param context
 * @param type
 * @return
 */
public static boolean isConnectedMobile(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

/**
 * Check if there is fast connectivity
 * @param context
 * @return
 */
public static boolean isConnectedFast(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && NetworkManagerUtils.isConnectionFast(info.getType(),info.getSubtype()));
}

/**
 * Check if the connection is fast
 * @param type
 * @param subType
 * @return
 */
public static boolean isConnectionFast(int type, int subType){
    if(type== ConnectivityManager.TYPE_WIFI){
        return true;
    }else if(type==ConnectivityManager.TYPE_MOBILE){
        switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
        }
    }else{
        return false;
    }
}
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";
            default:
                return "?";
        }
    }
    return "?";
}
}

use this following the class pass the context you will the get network status like network type,fast network,etc.

Solution 10 - Android

String active_network = ((ConnectivityManager)
    .getSystemService(Context.CONNECTIVITY_SERVICE))
    .getActiveNetworkInfo().getSubtypeName();

should get you the network name

Solution 11 - Android

You can try this:

public String ConnectionQuality() {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return "UNKNOWN";
    }
	
    if(info.getType() == ConnectivityManager.TYPE_WIFI) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		int numberOfLevels = 5;
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
		if(level == 2 )
				return "POOR";
			else if(level == 3 )
				return "MODERATE";
			else if(level == 4 )
				return "GOOD";
			else if(level == 5 )
				return "EXCELLENT";
			else
			return "UNKNOWN";
		}else if(info.getType() == ConnectivityManager.TYPE_MOBILE) {
			int networkClass = getNetworkClass(getNetworkType(context));
			if(networkClass == 1)
				return "POOR";
			else if(networkClass == 2 )
				return "GOOD";
			else if(networkClass == 3 )
				return "EXCELLENT";
			else
				return "UNKNOWN";
		}else
			return "UNKNOWN";  
}
  
public NetworkInfo getInfo(Context context) {
	return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
}
  
public int getNetworkClass(int networkType) {
	try {
      return getNetworkClassReflect(networkType);
    }catch (Exception ignored) {
    }

    switch (networkType) {
      case TelephonyManager.NETWORK_TYPE_GPRS:
      case 16: // TelephonyManager.NETWORK_TYPE_GSM:
      case TelephonyManager.NETWORK_TYPE_EDGE:
      case TelephonyManager.NETWORK_TYPE_CDMA:
      case TelephonyManager.NETWORK_TYPE_1xRTT:
      case TelephonyManager.NETWORK_TYPE_IDEN:
        return 1;
      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:
      case TelephonyManager.NETWORK_TYPE_EHRPD:
      case TelephonyManager.NETWORK_TYPE_HSPAP:
      case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:
        return 2;
      case TelephonyManager.NETWORK_TYPE_LTE:
      case 18: // TelephonyManager.NETWORK_TYPE_IWLAN:
        return 3;
      default:
        return 0;
    }
}
  
private int getNetworkClassReflect(int networkType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {  
    Method getNetworkClass = TelephonyManager.class.getDeclaredMethod("getNetworkClass", int.class);
    if (!getNetworkClass.isAccessible()) {
      getNetworkClass.setAccessible(true);
    }
    return (Integer) getNetworkClass.invoke(null, networkType);	
}
  
public static int getNetworkType(Context context) {
    return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType();
}

Solution 12 - Android

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);

Solution 13 - Android

Currently, only MOBILE and WIFI is supported. Take a look and human readable type function.

Solution 14 - Android

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
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhpiqueView Question on Stackoverflow
Solution 1 - AndroidEmil DavtyanView Answer on Stackoverflow
Solution 2 - Androidben75View Answer on Stackoverflow
Solution 3 - AndroidtwkView Answer on Stackoverflow
Solution 4 - AndroidSuchintyaView Answer on Stackoverflow
Solution 5 - AndroidJared RummlerView Answer on Stackoverflow
Solution 6 - AndroidShafqat KamalView Answer on Stackoverflow
Solution 7 - AndroidChapzView Answer on Stackoverflow
Solution 8 - AndroidRahul NaganeView Answer on Stackoverflow
Solution 9 - AndroidsanjayView Answer on Stackoverflow
Solution 10 - Androidj2emanueView Answer on Stackoverflow
Solution 11 - Androidsaid_devView Answer on Stackoverflow
Solution 12 - AndroidHasan El-HefnawyView Answer on Stackoverflow
Solution 13 - AndroidjarekrozanskiView Answer on Stackoverflow
Solution 14 - AndroidAlex ShevelevView Answer on Stackoverflow