Implementing Internet Connectivity Checker in Android Apps

Implementing Internet Connectivity Checker in Android Apps

Photo by Rami Al-zayat on Unsplash

“How do we check if there is an active internet connection?”

Basically, we can ping or connect to any server to see whether this ping or connection is successful or not.
If you have your own back-end server, you may prefer to try to connect your app to the server to make sure that the device has an internet connection and your server is not down at the same time.
We can also connect to Google’s servers as they are unlikely to be down (or for a long time).
To optimize our class implementation (we’ll call it NetworkConnectivity), it’s good to check a device’s network connection using ConnectivityManager so that if WiFi or mobile data is turned off or even WiFi is turned on but there is no network the device is connected to, we don’t have to make requests to any servers.

Enough talk!

First of all, add internet and network state permissions in your app manifest:

Back to our business

To ping Google’s server, basically, we can do that with a few lines of code:

Unreliable approach!

That’s it!

To check internet connectivity in an activity: