Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active Aug 18, 2021
Embed
What would you like to do?
/**
* Network utility to get current state of internet connection
*/
val Context.currentConnectivityState: ConnectionState
get() {
val connectivityManager =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return getCurrentConnectivityState(connectivityManager)
}
private fun getCurrentConnectivityState(
connectivityManager: ConnectivityManager
): ConnectionState {
val connected = connectivityManager.allNetworks.any { network ->
connectivityManager.getNetworkCapabilities(network)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
?: false
}
return if (connected) ConnectionState.Available else ConnectionState.Unavailable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment