Merge branch 'github/main'

pull/836/head
Automerger 1 year ago
commit 3be2ed6ba8

@ -21,6 +21,7 @@ import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback import android.net.ConnectivityManager.NetworkCallback
import android.net.Network import android.net.Network
import android.net.NetworkCapabilities import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.NetworkRequest.Builder import android.net.NetworkRequest.Builder
import android.os.Build.VERSION import android.os.Build.VERSION
import android.os.Build.VERSION_CODES import android.os.Build.VERSION_CODES
@ -44,36 +45,33 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
} }
/** /**
* Sends the latest connectivity status to the underlying channel. * The callback's methods are invoked on changes to *any* network matching the [NetworkRequest],
*/ * not just the active network. So we can simply track the presence (or absence) of such [Network].
fun update() {
channel.trySend(connectivityManager.isCurrentlyConnected())
}
/**
* The callback's methods are invoked on changes to *any* network, not just the active
* network. So to check for network connectivity, one must query the active network of the
* ConnectivityManager.
*/ */
val callback = object : NetworkCallback() { val callback = object : NetworkCallback() {
override fun onAvailable(network: Network) = update()
override fun onLost(network: Network) = update() private val networks = mutableSetOf<Network>()
override fun onCapabilitiesChanged( override fun onAvailable(network: Network) {
network: Network, networks += network
networkCapabilities: NetworkCapabilities, channel.trySend(true)
) = update() }
override fun onLost(network: Network) {
networks -= network
channel.trySend(networks.isNotEmpty())
}
} }
connectivityManager.registerNetworkCallback( val request = Builder()
Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build()
.build(), connectivityManager.registerNetworkCallback(request, callback)
callback,
)
update() /**
* Sends the latest connectivity status to the underlying channel.
*/
channel.trySend(connectivityManager.isCurrentlyConnected())
awaitClose { awaitClose {
connectivityManager.unregisterNetworkCallback(callback) connectivityManager.unregisterNetworkCallback(callback)
@ -87,6 +85,7 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
activeNetwork activeNetwork
?.let(::getNetworkCapabilities) ?.let(::getNetworkCapabilities)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
else -> activeNetworkInfo?.isConnected else -> activeNetworkInfo?.isConnected
} ?: false } ?: false
} }

Loading…
Cancel
Save