If you are developing an Android app you may already fetching information from internet. While doing so there is a chance that internet connection is not available on users handset. Hence its always a good idea to check the network state before performing any task that requires internet connection.
You might also want to check what kind of internet connection is available in handset. For example is wifi currently enabled? or is mobile data network is connected.
Check Internet Connection
Here is a simple code snippet that will help you identify what kind of internet connection a user has on her device.
First we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.
Permissions required to access network state:
Now check following utility class NetworkUtil. It has method getConnectivityStatus which returns an int constant depending on current network connection. If wifi is enabled, this method will return TYPE_WIFI. Similarly for mobile data network is returns TYPE_MOBILE. You got the idea!!
There is also method getConnectivityStatusString which returns current network state as a more readable string.
You can use this utility class in your android app to check the network state of the device at any moment.
Now this code will return you the current network state whenever the utility method is called. What if you want to do something in your android app when network state changes? Lets say when Wifi is disabled, you need to put your android app service to sleep so that it does not perform certain task. Now this is just one usecase. The idea is to create a hook which gets called whenever network state changes. And you can write your custom code in this hook to handle the change in network state.
Broadcast Receiver to handle changes in Network state
You can easily handle the changes in network state by creating your own Broadcast Receiver. Following is a broadcast receiver class where we handle the changes in network.
Check onReceive() method. This method will be called when state of network changes. Here we are just creating a Toast message and displaying current network state. You can write your custom code in here to handle changes in connection state.
We defined our broadcast receiver class in menifest file. Also we defined two intent CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED. Thus this will register our receiver for given intents. Whenever there is change in network state, android will fire these intents and our broadcast receiver will be called.
Below is complete AndroidMenifest.xml file.
Run this demo in android emulator or actual device.
When Wifi is enabled, you’ll see a Toast message with message.
Now disable Wifi. The toast message will show you message that internet connection is not available.
Now enable mobile data network. The same will be show in toast message as soon as you enable mobile data connection.