Last active
July 28, 2021 13:12
-
-
Save sowakillian/3f4a0e5499780dace9016ef699e839e4 to your computer and use it in GitHub Desktop.
Monitor network in realtime with StateFlow and ConnectivityManager on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NetworkManager() { | |
val context = YourApplication.appContext | |
private lateinit var networkCallback: ConnectivityManager.NetworkCallback | |
private val connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager | |
private val _isNetworkAvailable = MutableStateFlow(false) | |
val isNetworkAvailable: StateFlow<Boolean> = _isNetworkAvailable.asStateFlow() | |
init { | |
networkCallback = createNetworkCallback() | |
val networkRequest = NetworkRequest.Builder() | |
.addCapability(NET_CAPABILITY_INTERNET) | |
.build() | |
connectivityManager.registerNetworkCallback(networkRequest, networkCallback) | |
} | |
private fun updateNetworkAvailability(newState: Boolean) { | |
_isNetworkAvailable.value = newState | |
} | |
private fun createNetworkCallback() = object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
val networkCapabilities = connectivityManager.getNetworkCapabilities(network) | |
val hasInternetCapability = networkCapabilities?.hasCapability(NET_CAPABILITY_INTERNET) | |
if (hasInternetCapability == true) { | |
updateNetworkAvailability(true) | |
} | |
} | |
override fun onLost(network: Network) { | |
updateNetworkAvailability(false) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment