Network connection checking – Android


When we build an app which connects to the internet or need a network connection to do a particular task, it is always a good practice that we check the network connection. Doing so, we can show the user if the network is connected or not.

Here in this post, I am going to give you a working example of network connection checking in Android and I am also going to explain how does it work in detail.

The class we need to check network connection is ConnectivityManager. And we also need an instance of the ConnectivityManager class. For that, we need to call getSystemService(Context.CONNECTIVITY_SERVICE).

Let’s see a working example first.We are going to make a simple app which has two activities. In the first activity, there is a button. Clicking on the button, the network connection is checked. If it returns true the second activity will open. If it returns false, the user will see a warning message, saying “Check your network connection”.


Code – Below is the complete code of this app. 

As you can see, if there is a network connection the second activity or WelcomeActivity will open.
In have nothing special is class. Just a static TextView with ‘Welcome’ text in it.

Coming to the class. In this class, we have a ‘Next’ button. Clicking on which the second activity will open. We have used intent to go to the second activity.

We have also used a toast message to show the network status.

Since we have used two activities here, don’t forget to add WelcomeActivity in your AndroidManifest.xml file.

Another thing you need to declare in your manifest is permission for network state since our app needs information about the network. So declare permission ACCESS_NETWORK_STATE in your AndroidManifest.xml file.

This is our manifest file
To test the app if it is working or not –

First turn off the data connection. To do so, follow the simple steps –

If you are using an emulator – Go to phone’s ‘Settings‘ – click ‘More‘ – click ‘Cellular network  disable ‘Data enabled‘. 

Now run the app and check if you can go to the second activity, which is WelcomeActivity. Now enable the option ‘Data enabled‘ and re-launch the app again and see if you can go the next activity.

You May Also Like


Leave a Reply

Your email address will not be published. Required fields are marked *