Created
June 5, 2020 11:21
Star
You must be signed in to star a gist
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
fun Context.hasNetwork(): Boolean { | |
val connectivityManager = 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(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true | |
else -> false | |
} | |
} else { | |
connectivityManager.activeNetworkInfo?.run { | |
return when (type) { | |
ConnectivityManager.TYPE_WIFI -> true | |
ConnectivityManager.TYPE_MOBILE -> true | |
ConnectivityManager.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