Skip to content

Commit

Permalink
NetworkConnectedReceiver will now be explicily registered and unregis…
Browse files Browse the repository at this point in the history
…tered
  • Loading branch information
this-Aditya committed Nov 3, 2024
1 parent 838c2de commit 981ae83
Showing 1 changed file with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.callbackFlow
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.atomic.AtomicBoolean

/**
* Keeps track of whether there is a network connection (e.g., WiFi or Ethernet).
Expand All @@ -49,24 +52,36 @@ class NetworkConnectedReceiver(
context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
) { "No connectivity manager available" }

val state: Flow<NetworkState>
val isMonitoring: AtomicBoolean = AtomicBoolean(false)

init {
var state: Flow<NetworkState>? = null

fun monitor() {
if (isMonitoring.get()) {
logger.info("Network receiver is already being monitored")
return
}
state = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
callbackFlow {
val callback = createCallback()
connectivityManager.registerDefaultNetworkCallback(callback)
isMonitoring.set(true)
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
state = null
isMonitoring.set(false)
}
}
} else {
callbackFlow {
val receiver = createBroadcastReceiver()
@Suppress("DEPRECATION")
context.registerReceiver(receiver, IntentFilter(CONNECTIVITY_ACTION))
isMonitoring.set(true)
awaitClose {
context.unregisterReceiver(receiver)
state = null
isMonitoring.set(false)
}
}
}
Expand Down Expand Up @@ -145,4 +160,8 @@ class NetworkConnectedReceiver(
object Disconnected : NetworkState(hasWifiOrEthernet = false)
class Connected(hasWifiOrEthernet: Boolean) : NetworkState(hasWifiOrEthernet)
}

companion object {
private val logger: Logger = LoggerFactory.getLogger(NetworkConnectedReceiver::class.java)
}
}

0 comments on commit 981ae83

Please sign in to comment.