@@ -21,6 +21,7 @@ import android.net.ConnectivityManager
2121import android.net.ConnectivityManager.NetworkCallback
2222import android.net.Network
2323import android.net.NetworkCapabilities
24+ import android.net.NetworkRequest
2425import android.net.NetworkRequest.Builder
2526import android.os.Build.VERSION
2627import android.os.Build.VERSION_CODES
@@ -44,36 +45,33 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
4445 }
4546
4647 /* *
47- * Sends the latest connectivity status to the underlying channel.
48- */
49- fun update () {
50- channel.trySend(connectivityManager.isCurrentlyConnected())
51- }
52-
53- /* *
54- * The callback's methods are invoked on changes to *any* network, not just the active
55- * network. So to check for network connectivity, one must query the active network of the
56- * ConnectivityManager.
48+ * The callback's methods are invoked on changes to *any* network matching the [NetworkRequest],
49+ * not just the active network. So we can simply track the presence (or absence) of such [Network].
5750 */
5851 val callback = object : NetworkCallback () {
59- override fun onAvailable (network : Network ) = update()
6052
61- override fun onLost ( network : Network ) = update ()
53+ private val networks = mutableSetOf< Network > ()
6254
63- override fun onCapabilitiesChanged (
64- network : Network ,
65- networkCapabilities : NetworkCapabilities ,
66- ) = update()
55+ override fun onAvailable (network : Network ) {
56+ networks + = network
57+ channel.trySend(true )
58+ }
59+
60+ override fun onLost (network : Network ) {
61+ networks - = network
62+ channel.trySend(networks.isNotEmpty())
63+ }
6764 }
6865
69- connectivityManager.registerNetworkCallback(
70- Builder ()
71- .addCapability(NetworkCapabilities .NET_CAPABILITY_INTERNET )
72- .build(),
73- callback,
74- )
66+ val request = Builder ()
67+ .addCapability(NetworkCapabilities .NET_CAPABILITY_INTERNET )
68+ .build()
69+ connectivityManager.registerNetworkCallback(request, callback)
7570
76- update()
71+ /* *
72+ * Sends the latest connectivity status to the underlying channel.
73+ */
74+ channel.trySend(connectivityManager.isCurrentlyConnected())
7775
7876 awaitClose {
7977 connectivityManager.unregisterNetworkCallback(callback)
@@ -87,6 +85,7 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
8785 activeNetwork
8886 ?.let (::getNetworkCapabilities)
8987 ?.hasCapability(NetworkCapabilities .NET_CAPABILITY_INTERNET )
88+
9089 else -> activeNetworkInfo?.isConnected
9190 } ? : false
9291}
0 commit comments