Created
June 30, 2022 09:44
-
-
Save muhammad-hamza-shahid/5aa222306dcce00b8d50b38da1b36358 to your computer and use it in GitHub Desktop.
Internet Manger to check connection status
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
object InternetManager { | |
fun checkForInternet(context: Context): Boolean { | |
// register activity with the connectivity manager service | |
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
// if the android version is equal to M | |
// or greater we need to use the | |
// NetworkCapabilities to check what type of | |
// network has the internet connection | |
// Returns a Network object corresponding to | |
// the currently active default data network. | |
val network = connectivityManager.activeNetwork ?: return false | |
// Representation of the capabilities of an active network. | |
val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false | |
return when { | |
// Indicates this network uses a Wi-Fi transport, | |
// or WiFi has network connectivity | |
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
// Indicates this network uses a Cellular transport. or | |
// Cellular has network connectivity | |
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
// else return false | |
else -> false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment