Skip to content

Instantly share code, notes, and snippets.

@frestoinc
Created May 18, 2020 20:08
Show Gist options
  • Save frestoinc/2fb199b7a9263e060e4c4d3732b51eaa to your computer and use it in GitHub Desktop.
Save frestoinc/2fb199b7a9263e060e4c4d3732b51eaa to your computer and use it in GitHub Desktop.
private fun hasInternetConnection(): Boolean {
val connectivityManager = getApplication<NewsApplication>().getSystemService(
Context.CONNECTIVITY_SERVICE
) as ConnectivityManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return when {
capabilities.hasTransport(TRANSPORT_WIFI) -> true
capabilities.hasTransport(TRANSPORT_CELLULAR) -> true
capabilities.hasTransport(TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.activeNetworkInfo?.run {
return when(type) {
TYPE_WIFI -> true
TYPE_MOBILE -> true
TYPE_ETHERNET -> true
else -> false
}
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment