Created
April 12, 2021 16:56
-
-
Save rafayali/6dd986421c7109071345caaa9a5b18af to your computer and use it in GitHub Desktop.
Checks for internet connectivity from API 21 and above
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 NetworkUtilities { | |
fun isInternetConnected(context: Context): Boolean { | |
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
val networkCapabilities = | |
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) | |
if (networkCapabilities != null && | |
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && | |
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) | |
) { | |
return true | |
} else { | |
return false | |
} | |
} else { | |
val networkInfo = connectivityManager.activeNetworkInfo | |
if (networkInfo != null && networkInfo.detailedState == NetworkInfo.DetailedState.CONNECTED) { | |
return true | |
} else { | |
return false | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment