Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Monitor Internet Connection in Android Using Kotlin and LiveData

Siva Ganesh Kantamani
Better Programming
Published in
5 min readJul 27, 2021
person using the touchpad on a notebook computer
Photo by Sergey Zolkin on Unsplash

Introduction

One of the basic requirements of any mobile application these days is an internet connection. If you’ve used any mobile application for a while, you might have seen a small banner with a red or green background to indicate the network connection status at the top or bottom part of the screen, based on the app UI.

Implementing this feature has two advantages. First, the user is aware that they are offline so they can take appropriate action. Second, if you implement it correctly, it’ll be aesthetically pleasing with your UI.

Prerequisites

This is one of the features that seems easy to handle yet involves a deeper understanding of how things work in ConnectivityManager. Here we use ConnectivityManager to get the network connection’s information, and then we use LiveData to communicate the result to the view in a sealed class format. We’ll also use Kotlin coroutines to solve a real-time problem with Android APIs.

Before going any further, please go through the following articles if you’re not aware of any of the above-discussed concepts:

Sealed Class

According to Kotlin docs, Sealed classes and interfaces represent restricted class hierarchies that provide more control over inheritance.

Get started by creating a simple sealed class with two states, network available and not available. Sealed classes are the perfect fit for this purpose, and they make it easy to handle states at the class site. In our case, it’s the view. Have a look at a simple sealed class:

sealed class NetworkStatus {
object Available : NetworkStatus()
object Unavailable : NetworkStatus()
}

You can pass the message to show in each state as a parameter if you need it.

Analyzing Network Monitor Class

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (5)

Write a response