Creating a network sensing activity in Android

Prashant Barahi
MindOrks
Published in
2 min readJan 2, 2019

Have you ever noticed a persistent snack bar in Android’s YouTube app or LinkedIn- that shows up whenever you have lost your internet connection? Ever wanted to implement the same in your own Android application? In that case, seek no further- we are going to do just that — in a clean and “DRY” way.

Lets start by creating a view for our implementation of SnackBar. We will call it custom_snackbar.xml and we will inflate it on CustomSnackbar class as follows:

Next, we are going to setup a class, that will monitor the status of device network connection and will notify our listener whenever it changes.

Great! Now, we will create a base activity class that will initialize our ConnectionStateMonitor class and call its enable() method to start “observing” the network connectivity. We might have to manually check for network connection in onResume() just for “foolproof-ness” of our implementation.

Finally, to show a snackbar whenever the network connection is lost, we will just have to extend our activity class to NetworkSensingActivity class.

Final Result:

Things to note:

  1. The android support library v28.0.0 might give you memory leaks when using SnackBar. This issue was filed here; and has been fixed in androidx.appcompat:appcompat:1.1.0+.

--

--