Identify the type of connection 3g, 4g and / or Wifi

4

Good morning!

I need to check the type of connection that the device is for example 2g, 3g, 4g or Wifi.

Because after checking the type of connection I need to limit the device to perform some actions.

Someone could help me, thank you.

Att.

    
asked by anonymous 05.02.2016 / 13:57

1 answer

1

First add this tag to the project manifest to allow access to the connection status

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

Then create this function where it is most convenient:

public static String getNetworkClass(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);      
    NetworkInfo info = cm.getActiveNetworkInfo();

    if(info==null || !info.isConnected())
        return "-"; //sem conexão
    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 : troque por 11
                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 : troque por 14
            case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : troque por 12
            case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : troque por 15
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : troque por 13
                return "4G";
            default:
                return "?";
         }
    }
    return "?";
}

This basically answers the need for your question because with the result of the return you can decide what to do on, I recommend consulting the links of Diego's commentary for advanced information

    
05.02.2016 / 15:04