Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active August 18, 2021 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatilShreyas/147f44e8e92322c9aa183a03f1e57ccd to your computer and use it in GitHub Desktop.
Save PatilShreyas/147f44e8e92322c9aa183a03f1e57ccd to your computer and use it in GitHub Desktop.
/**
* 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