How to Monitor/Observe Network Availability for Android Projects
Network/Cellular data is widely used in Android Projects. Most of the app currently exist in the play store have API call some way or another. As in the nature of API (Application Programming Interface), you are interacting with another application that your project does not have any authority in the codebase. Sometimes, these APIs fail. And, when they fail, it is very important to show proper error message to the customers about what went wrong. Otherwise, the users will think that your app is not working properly.
One common problem that API might be failing due to the network availability. In case there is no cellular connection available in the user’s device, the API might fail. Since we as developers know that it does not make sense to use resources to launch a network call when there is no cellular/wifi connection available, a message can be prompted to the users regarding to the network availability. Thus, the customers can try to find a network connection and then start using your application.
In this article, we will try to cover how we can monitor, observe, or collect the network availability so that the user will not need to re-launch your app when they get a good connection. We will use ConnectivityManager
service, which is already provided in Android SDK.
Table of Contents
- What is ConnectivityManager?
- 1. Introducing Network Callback
- 2. Creating Network Request (< API 24)
- 3. Observing Network Availability
- 4. Bonus
- Conclusion
What is ConnectivityManager?
ConnectivityManager
is a system service in Android platform. It is responsible to answer queries about network connectivity. ConnectivityManager allows us to monitor connectivity changes via using callbacks or Broadcast intents, and gives us specific details on the connection type (Cellular, WiFi, etc.). Also, it provides an API that allows applications request and select networks for their data traffic.
Please visit my own website to read rest of the blog
Thank you very much
Happy Coding