Last active
March 30, 2024 10:23
-
-
Save mohitkumarsoni/cb1baf68f03658a5bbf5e5546aa17806 to your computer and use it in GitHub Desktop.
check internet connection in android
This file contains hidden or 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
private fun isDeviceConnectedToInternet(): 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_ETHERNET) -> true | |
capabilities.hasTransport(TRANSPORT_CELLULAR) -> true | |
else -> false | |
} | |
} else { | |
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