Network Status Monitoring

In mobile application development, network connection status is one of the key factors determining user experience. Users expect applications to provide appropriate feedback when going offline, experiencing poor connectivity, or recovering a connection—for example, by displaying loading indicators, switching to an offline mode, or automatically retrying requests. The Android operating system provides powerful tools for perceiving the device's current network connection status, with ConnectivityManager being the core listener component. By monitoring changes in network state, developers can build more robust and intelligent applications, thereby enhancing user experience across various network environments.
To begin listening to network states, you first need to obtain the ConnectivityManager object from your application's context. In newer versions of Android API (API 28 and above), it is recommended to use the ContextCompat.getSystemService() method to retrieve the service to ensure compatibility across different devices.

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCallback;
import android.net.Network;

public class NetworkMonitor {
    private static ConnectivityManager connectivityManager;

    public static void init(Context context) {
        if (connectivityManager == null) {
            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
    }

    public static void registerNetworkCallback(Context context, NetworkCallback callback) {
        if (connectivityManager != null) {
            connectivityManager.registerNetworkCallback(callback, null, null);
        }
    }
}

This code demonstrates how to initialize and register a callback function so that corresponding logic is triggered upon detecting changes in network state. Using null as the initial network parameter means we will listen for all types of network connection changes.

Implementing Callback Logic for Network State Changes

Once successfully registered, ConnectivityManager will automatically invoke the specified NetworkCallback when it detects a change in network status. The callback interface provides rich methods that allow developers to retrieve the currently active network, determine the network type, and handle specific events.

public class NetworkStateCallback extends ConnectivityManager.NetworkCallback {

    @Override
    public void available(Network network) {
        // Execute this method when a new network becomes available
        Log.d("NetworkMonitor", "New network available: " + network.getName());
        updateUIForNewNetwork(network);
    }

    @Override
    public void disconnected(Network network) {
        // Execute this method when the specified network connection is disconnected
        Log.d("NetworkMonitor", "Network disconnected: " + network.getName());
        switchToOfflineMode();
    }

    private void updateUIForNewNetwork(Network network) {
        String type = network.getType().toString();
        if ("ETH".equals(type)) {
            // Handle Ethernet connection
            showWifiIcon();
        } else if ("WIFI".equals(type)) {
            // Handle Wi-Fi connection
            showHighSpeedIndicator();
        }
    }

    private void switchToOfflineMode() {
        // Logic to switch to offline mode after disconnecting from the network
        displayLoadingSpinner();
    }
}

By overriding methods such as available and disconnected, developers can precisely control application behavior under different network states. For instance, when a Wi-Fi connection is detected, you can prompt the user that they are connected to a high-speed network; conversely, when the network disconnects, it automatically switches to offline mode or displays a retry button.

Handling Network Type and Quality Assessment

Beyond basic connectivity status, understanding the specific type and quality of the current network is crucial for optimizing user experience. ConnectivityManager allows developers to query detailed information about networks, including IP addresses, MAC addresses, and network types. Combined with the NetworkCapabilities API, you can further evaluate network speed, bandwidth, and mobility characteristics.

import android.net.NetworkInfo;
import android.net.ConnectivityManager;

public class NetworkTypeChecker {
    public static String getNetworkType(ConnectivityManager cm) {
        Network activeNetwork = cm.getActiveNetwork();
        if (activeNetwork == null || !cm.isActiveNetwork()) {
            return "No Active Network";
        }
        
        NetworkInfo networkInfo = cm.getNetworkInfo(activeNetwork);
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getType().toString();
            return type;
        }
        return "Unreachable";
    }
}

In practical applications, developers can adopt different strategies based on the returned network type. For mobile data networks, for example, you might increase retry counts or enable background synchronization; whereas for Wi-Fi networks, faster loading speeds and smoother media playback experiences can be provided. This fine-grained control capability is foundational to building high-quality Android applications.