javaandroidnetworkinfo

Difference between NetworkInfo.isConnected() and NetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED. What to use?


I want to know which method will be precise to check the network state for successfully getting connected.


Solution

  • So if we look at the source code of NetworkInfo.java class you will see that the network detailed states are declared as Enum,

    public enum DetailedState {
            /** Ready to start data connection setup. */
            IDLE,
            /** Searching for an available access point. */
            SCANNING,
            /** Currently setting up data connection. */
            CONNECTING,
            /** Network link established, performing authentication. */
            AUTHENTICATING,
            /** Awaiting response from DHCP server in order to assign IP address information. */
            OBTAINING_IPADDR,
            /** IP traffic should be available. */
            CONNECTED,
            /** IP traffic is suspended */
            SUSPENDED,
            /** Currently tearing down data connection. */
            DISCONNECTING,
            /** IP traffic not available. */
            DISCONNECTED,
            /** Attempt to connect failed. */
            FAILED,
            /** Access to this network is blocked. */
            BLOCKED,
            /** Link has poor connectivity. */
            VERIFYING_POOR_LINK,
            /** Checking if network is a captive portal */
            CAPTIVE_PORTAL_CHECK
        }
    

    But if you read the comments for these DetailedState it says below about these

    The fine-grained state of a network connection. This level of detail is probably of interest to few applications. Most should use android.net.NetworkInfo.State State instead.

    The isConnected() method inside the NetworkInfo.java class is checking against the State.CONNECTED State only,

    public boolean isConnected() {
            synchronized (this) {
                return mState == State.CONNECTED;
            }
        }
    

    Essentially if you use

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();
    

    that should suffice as above code will query the active network and determine if it has Internet connectivity. Once you know it, you can proceed with accessing internet resource.