How to detect Internet Connectivity Change in Android?
In some of the applications we want to know if internet connection has dropped or established. If internet connection is dropped, we might store data in local database and when internet connection is established again, we could send this data to the backend.
If you want to send the data as soon as internet connection is established you can find ‘WorkManager’ class useful for that purpose, but scheduling Jobs is not a purpose of this article.
In this article we’ll explore two approaches for listening internet connectivity change in Android apps. These approaches can detect internet connectivity change from both WiFi and mobile data internet providers.
So, let’s start. 😃
Using Broadcast Receiver
In this approach we are going to use broadcast receiver in order to receive ‘CONNECTIVITY_ACTION’. Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest and that’s the reason why we declared broadcast receiver in abstract class:
Methods for registering connectivity change contains also lifecycle observer which unregister broadcast receiver in ‘ON_DESTROY’ lifecycle event, so we don’t need to unregister it manually.
If we want to start listening internet connectivity change in activity, we could invoke it like:
Using ‘ConnectivityManager’ class
The following code demonstrates how we can use ‘ConnectivityManager’ class and appropriate callback for listening network change events:
Callback ‘networkCallback’ will receive connection-established or connection-dropped events. We can see that ‘ConnectivityManager’ class has different methods for registering network callback on different Android API so they can work nicely, on different Android versions.
If we want to start listening for internet connectivity change, we can start it in ‘onCreate’ method of activity, like:
The only limitation of the code from above is that is supported from Android API version 21 (and that’s why our method for listening internet connectivity has ‘RequiresApi’ annotation), so this method won’t work on applications that are targeted to API version smaller then 21.
Because we’ve started listener in ‘onCreate’ method, we have to unregister it in ‘onDestroy’ method by invoking the following code:
Method ‘log’ is used for logging messages in android system messages log.
In this article we have seen two approaches for listening the connectivity change in Android apps and it’s on you which approach you’ll decide to use, based on the minimum Android API version that your app must support and your subjective feeling which approach is the best.
Happy coding! 😃
[1]: “How to fix No Internet Connection Problem with Three Solutions”, IT Phobia, https://itphobia.com/how-to-fix-no-internet-connection/.
Accessed 15 Feb. 2021.