SoFunction
Updated on 2025-04-10

How to determine network type of Android (2g, 3g or wifi)

This article describes the method of Android judging network types. Share it for your reference, as follows:

Determine whether the network type is wifi, 3G, or 2G network, and perform different processing on different networks. Now we will sort out the judgment methods for everyone for reference

Note: I have tested the data mobile 2G, China Unicom 2G, China Unicom 3G, and Wifi below. I don’t have a telecom card at the moment, so there is no verification. My colleagues with telecom mobile phones can verify it and send the results to everyone after verification.

ConnectivityManager connectMgr = (ConnectivityManager) this
    .getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = ();

1. Determine whether the network is wifi, and must make a non-empty judgment before making a judgment, if there is no network connection

info ==null
() == ConnectivityManager.TYPE_WIFI

2. Determine whether it is a mobile network

info !=null && () == ConnectivityManager.TYPE_MOBILE

Mobile networks make detailed distinctions:

() Use getSubtype() here, not getType(), getType() returns 0 or 1, which is to distinguish whether it is a mobile network or a wifi

()The value list is as follows:

* NETWORK_TYPE_CDMA The network type is CDMA
* NETWORK_TYPE_EDGE The network type is EDGE
* NETWORK_TYPE_EVDO_0 The network type is EVDO0
* NETWORK_TYPE_EVDO_A The network type is EVDOA
* NETWORK_TYPE_GPRS The network type is GPRS
* NETWORK_TYPE_HSDPA The network type is HSDPA
* NETWORK_TYPE_HSPA The network type is HSPA
* NETWORK_TYPE_HSUPA The network type is HSUPA
* NETWORK_TYPE_UMTS The network type is UMTS

Unicom's 3G is UMTS or HSDPA, Mobile and Unicom's 2G is GPRS or EDGE, Telecom's 2G is CDMA, and Telecom's 3G is EVDO

Android get the IP address of your phone

private String getPhoneIp() {
    try {
      for (Enumeration<NetworkInterface> en = (); ();) {
        NetworkInterface intf = ();
        for (Enumeration<InetAddress> enumIpAddr = (); ();) {
          InetAddress inetAddress = ();
          if (!() && inetAddress instanceof Inet4Address) {
          //if (!() && inetAddress instanceof Inet6Address) {
            return ().toString();
          }
        }
      }
    } catch (Exception e) {
    }
    return "";
}

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android database operation skills summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.