Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mohitkumarsoni/3f7edc80c83c0462f498c1b6095feb3c to your computer and use it in GitHub Desktop.
Save mohitkumarsoni/3f7edc80c83c0462f498c1b6095feb3c to your computer and use it in GitHub Desktop.
private fun isDeviceConnectedToInternet() : Boolean {
val connectivityManager = getApplication<NewsApplication>().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
// if version SDK is above 23 (for device above Android 6)
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return when{
capabilities.hasTransport(TRANSPORT_WIFI) -> true
capabilities.hasTransport(TRANSPORT_ETHERNET) -> true
capabilities.hasTransport(TRANSPORT_CELLULAR) ->true
else -> false
}
}else{
// version SDK is below 23 (for older device below Android 6)
connectivityManager.activeNetworkInfo?.run {
return when (type) {
TYPE_WIFI -> true
TYPE_ETHERNET -> true
TYPE_MOBILE -> true
else -> false
}
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment