Check active internet connection on android device.

Most of the time we write some boilerplate to check if device has active internet connection or not. Connecting to a network doesn’t necessarily mean that device has active internet connection also. So for this I have created a library which you can include in your android projects (which requires internet permission) through maven repository. What this library does is, you can subscribe to internet connectivity changes and the subscriber will be notified of network changes (whether active internet connection is present or not). This library listens to network changes and whenever network gets available it checks for internet and notifies to the listeners.
To use the library follow the following steps

  1. Add the dependency as follows:
compile 'com.treebo:internetavailabilitychecker:1.0.1'

2. Initialise it in application’s onCreate() function. This is necessary step before starting using the library because it needs context to register connectivity broadcast receiver. It stores only weakreference to the context, so no need to worry about memory leaks. Also it does lazy registration of receiver; i.e. it registers receiver whenever first listener attaches to listen to internet changes and unregister itself when last listener stops listening.

InternetAvailabilityChecker.init(this);

3. Implement InternetConnectivityListener interface where ever you want to listen to internet connectivity changes (E.g. in activity, fragment or service).

public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {
    @Override
public void onInternetConnectivityChanged(boolean isConnected) {
//do something based on connectivity
}
}

4. Get instance of InternetAvailabilityChecker and Add listener whenever you want to start listening to connectivity changes (e.g. in activity’s onCreate() function). It keeps a weakreference to the subscriber and clears the references whenever subscriber gets destroyed (when there is no more strong reference referencing it).

mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
mInternetAvailabilityChecker.addInternetConnectivityListener(this);

5. Remove listener whenever you are done (e.g. in activity’s onDestroy, fragment’s onDetach or service’s onDestroy).

mInternetAvailabilityChecker
.removeInternetConnectivityChangeListener(this);

Code is pretty simple. You can also check the source code and sample app at Github. Total method count is 65 and DEX size is 10KB. Hope it will be useful in android projects and will save some time writing this boilerplate to listen to connectivity changes. Also please feel free to contribute in making the library code better.

Like what you read? Give Ankit Aggarwal a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.