Have you ever wanted to show different things to your user based on whether they are connected to the network or not? Well, Android provides a simple way to check for an active network connection.
Note: This is checking whether or not the device is connected to a network (and not whether it is connected to Internet or not).
The way Android provides to check for network connectivity is just 10 lines of code. But me being the lazy coder that I am, I just write that code inside a helper method once and then use that one-line method call everywhere that I need to check for connectivity.
As you can see in the code-block below, it is quite easy to wrap the connectivity check logic in a function.
You also need to have the ACCESS_NETWORK_STATE permission added in your manifest like below.
Done
Now anywhere that you need to check the connection, you only need to
If you know of a better way for this, contact me or tweet to me @varun_barad. You can even send me ideas for any other topics that you would like to know about.