In my code, I need to track the internet connection and make appropriate changes. First of all, I create a network request, then register a network callback using the ConnectivityManager
.
val networkCallback = createNetworkCallback()
val networkRequest = NetworkRequest.Builder()
.addCapability(NET_CAPABILITY_INTERNET)
.addTransportType(TRANSPORT_CELLULAR)
.addTransportType(TRANSPORT_WIFI)
.addTransportType(TRANSPORT_ETHERNET)
.build()
connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
Let's look at networkRequest
. The network I'm requesting need to have a NET_CAPABILITY_INTERNET
and some transport types which I've specified in the code.
Then I register a network callback. As per docs - Registers to receive notifications about all networks which satisfy the given NetworkRequest.
Means, e.g. I'll turn WI-FI on/off, the network callback will fire only if I've specified that transport type or corresponding capabilities inside the network request. Now the question is, when the networkCallback
triggers, do I need to check for the capabilities and transport types again?
override fun onAvailable(network: Network) {
val networkCapabilities = cm.getNetworkCapabilities(network)
val hasInternetCapabilities = networkCapabilities?.let {
return@let it.hasCapability(NET_CAPABILITY_INTERNET) or
it.hasTransport(TRANSPORT_WIFI) or
it.hasTransport(TRANSPORT_CELLULAR) or
it.hasTransport(TRANSPORT_ETHERNET)
} ?: false
}
}
As I've understood, if the network will not satisfy my networkRequest
, the check inside onAvailable()
is irrelevant because it won't execute. Thank you.