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

Asked

Viewed 923 times

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.

  • These links can help: http://stackoverflow.com/questions/2802472/detect-network-connection-type-on-android and http://stackoverflow.com/questions/9283765/how-to-determine-if-network-type-2g-3g-or-4g

  • 1

    Thank you Diego Felipe is being very helpful the links. Hug

1 answer

1


First add this tag to the project manifest to allow access to 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 meets the need for your question because with the result of Return you can decide what to do next, I recommend checking the links of Diego’s comment for advanced information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.