How to Observe Network Connection Status

Shrayan Bajracharya
2 min readFeb 28, 2022

--

Photo by Franck on Unsplash

In this article, we are going to listen to the changes in the status of the network connection.

A Demo

This is an example demonstrating the use of the snippet.

Toggling airplane mode to enable/disable network connectivity

I have updated the UI when the network status changes. A “No Connection” message is shown when there is no network and as the network is back “Back Online” is shown.

The Snippet We Are Going to Use

We are going to use the snippet NetworkUtils which is going to help us to observe changes in the network connection status.

How It Works

Inherits NetworkCallback

In this snippet, we have created an object NetworkUtils which inherits from ConnectivityManager.NetworkCallback().

As per the Android Developer documentation, ConnectivityManager.NetworkCallback() is:

Used for notifications about network changes. Should be extended by applications wanting notifications.

Registers NetworkCallback

In our getNetworkLiveData() function we are registering the NetworkCallback so that we can listen to the network state changes and receive notifications. The callbacks will continue to be called until either the application exits or unregisterNetworkCallback() is called.

Updates networkLiveData

We have created a new MutableLiveData member named networkLiveData that can be observed through the function getNetworkLiveData(). We are updating the networkLiveData through the overridden functions onAvailable() and onLost(). Whenever the network is available networkLiveData is set to true and whenever it is lost networkLiveData is set to false.

How to Use It

For using our NetworkUtils to check the availability of internet connection, we should observe the LiveData in our View i.e. Activity or Fragment.

Observe network status

We should handle our UI state according to the boolean value of isConnected.

Furthermore, we should add the following permission in our AndroidManifest.xml file for accessing the network state.

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

Thank you for reading. Hope it helped you! Have a great day and happy coding :)

References

I stumbled upon this code while going through different awesome repos in Github. Here is the link to the repo that contains this code. This repo belongs to PatilShreyas. Feel free to follow him on Github and check his awesome repos.

--

--

Responses (1)