How to monitor network connectivity in Android

Android devices have multiple network interfaces (e.g. WiFi and 3G/4G etc.) that allows them to go online and be connected to the outside world. At the same time, these network interfaces are prone to intermittent disconnection (for example, due to location, weather etc). Having knowledge of when the phone is connected (or disconnected) helps applications to act smartly when communicating over the internet. An example is automatically resuming pending downloads – without user intervention – when your network connection comes back online.

The following guide shows how you can monitor the network connectivity in Android, so your application can respond better when the network connectivity changes.

Android provides a system service called ConnectivityManager that allows us to subscribe to notifications when network state is changed. Network connectivity changes can be due one of the following events:

  1. Current network interface being disconnected
  2. A new network interface being connected
  3. Handover (also known as “fallover”) between two network interfaces (usually as a result of one of the two events above), such as WiFi being activated as a result of user coming home and all network traffic will be routed through WiFi as opposed to 3G.

We can use BroadcastReceivers to subscribe to network connectivity changes as follows:

  1. Create a BroadcastReceiver that will handle connectivity status notifications

    The BroadcastReceiver will be notified whenever the network status changes with the following information:

    • ConnectivityManager.EXTRA_NETWORK_INFO – A NetworkInfo object with network information that caused the status change.
    • ConnectivityManager.EXTRA_REASON– A String value about the reason of the connection failure, which can be null.
    • ConnectivityManager.EXTRA_IS_FAILOVER – A boolean value indicating whether the connection manager is failing over from a disconnected network or not.
    • ConnectivityManager.EXTRA_NO_CONNECTIVITY – A boolean value indicating there is no internet connectivity.
    • ConnectivityManager.EXTRA_EXTRA_INFO – A string value indicating the network state.
    • ConnectivityManager.EXTRA_OTHER_NETWORK_INFO – An optional field that contains NetworkInfo describing properties of a new network that is connected as a result of loss of connectivity
    public class MainActivity extends Activity {
       // rest of the code in the Activity are committed for clarity
    
    	private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    		@Override
    		public void onReceive(Context context, Intent intent) {
    			boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    			String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
                
    			NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    			NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
    						
    			// do application-specific task(s) based on the current network state, such 
    			// as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
    		}
    	};
    }
    

    More details about the CONNECTIVITY_ACTION can be found here

  2. Register the BroadcastReceiver within the application

    The next step is to register the BroadcastReceiver created in the previous step, so our application will actually receive network state change notifications.

    public class MainActivity extends Activity {
       // rest of the code in the Activity are committed for clarity
    
       /*
        * method to be invoked to register the receiver
        */
       private void registerReceivers() {    
           registerReceiver(mConnReceiver, 
               new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
       }
    }
    

  3. Add the necessary permissions to your application manifest.

    Need to add the android.permission.ACCESS_NETWORK_STATE permission to the application’s Manifest (AndroidManifest.xml) file to enable the application to consume the ConnectivityManager service.

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

5 responses to “How to monitor network connectivity in Android

  1. How can I implement app for traffics statistics ? At least five me some tips

  2. Hi,

    Nice guide! May I ask if this will be automated or do I need to create a service for it? Because I wanted my app to automate something whenever it is connected to my home network.

  3. Hi Nice… Tutorial.. but i found one major observation regarding this network connectivity action. In some devices it is working quite well, eg. Samsung galaxy… etc but in some other devices like acer E130, Micromax or low end androids, this is not working… !What might be the reason?? Thanks…

  4. That is an interesting observation. I never really tested this with the low-end models you mentioned (I’ve tested mainly with HTC Hero, Desire, Nexus One, Galaxy and Galaxy s2 but they all work without an issue).

    Can you verify that the receiver itself is getting called (log before you do anything within the receiver?). The only reason I can think of is one of the Intent attributes are not defined in the OS version on the low end device (which is possible if it is a heavily customised version of Android) and that is causing some issue. Otherwise, I am at a loss to explain your observations.

Leave a comment