Connectivity State on Android 10 and Above

Disclaimer
Most of modern apps rely on connectivity state in one way or another.
We as developers used to utilize the CONNECTIVITY_ACTION
broadcast receiver along with NetworkInfo
API to get the current network state.
And it’s been working like a charm for many years long, but it’s time to say goodbye since both of them have recently become deprecated in favor of NetworkCallback
.
While it will still work, it’s not wise to rely on the deprecated things in production code in the long run. Therefore, I’ll give you a quick walkthrough of the new API to get this thing done.
NetworkCallback
Let’s meet the modern and more efficient replacement — NetworkCallback
.
While registering the callback, you have a choice of either using registerDefaultNetworkCallback()
or registerNetworkCallback()
.
The first one is predefined to target the default network of a device while the second one requires an additional setup of NetworkRequest
object, but at the same time offers a much more advanced set of capabilities.
Since our use case is pretty simple, registerDefaultNetworkCallback()
(available on API 24+) completely satisfies our needs.
Let’s have an example:
In the example above, we register a listener observing the state of the default network on a device (in most cases it’s either wifi or cellular network). Pretty straightforward.
NOTE: If the default network is not available when you register a listener, then you don’t receive any callback. For this reason, you have to always propagate the initial state to all consumers manually.
Getting the connectivity state synchronously
Sometimes you might need to get the current state in the synchronous manner (available on API 23+):
ConnectivityManager
allows us to figure out the capabilities of the active network which is exactly what we want.
Backward Compatibility
Since the above functionality requires API 24+, we still need to provide the backward-compatible implementation to cover the rest of the devices.
Here is a simplified example of the solution we utilize in our project.
Extracting the common interface:
Switching to NetworkCallback
on API 24:
Keep using the broadcast receiver and NetworkInfo
on the older API:
For the complete implementation, check the sample project on Github.
That’s all folks! Feel free to go ahead and reuse this approach in your projects.