how to monitor network connectivity in android_aaron
June 22, 2011
Android devices have multiple network interfaces (eg 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 downloadswithout user interventionwhen 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: Current network interface being disconnectedA new network interface being connectedHandover (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: 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_INFOA 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_FAILOVERA boolean value indicating whether the connection manager is failing over from a disconnected network or not.ConnectivityManager.EXTRA_NO_CONNECTIVITYA boolean value indicating there is no internet connectivity.ConnectivityManager.EXTRA_EXTRA_INFOA string value indicating the network state.ConnectivityManager . EXTRA_OTHER_NETWORK_INFOAn optional field that contains NetworkInfo describing properties of a new network that is connected as a result of loss of connectivity More details about the CONNECTIVITY_ACTION can be found here 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. Add the necessary permissions to your application manifest. Need to add the android.permission.ACCESS_NETWORK_STATE strong> permission to the application Manifest (AndroidManifest.xml) file to enable the application to consume the ConnectivityManager service.
