I want to use the ConnectivityManager
which provides the getAllNetworkInfo()
method for checking the availability of network in Android. This method wa
For someone needs Kotlin version, (Below is same code with Maor Hadad's)
fun Context.isNetworkConnected(): Boolean {
val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val allNetworks = manager?.allNetworks?.let { it } ?: return false
allNetworks.forEach { network ->
val info = manager.getNetworkInfo(network)
if (info.state == NetworkInfo.State.CONNECTED) return true
}
} else {
val allNetworkInfo = manager?.allNetworkInfo?.let { it } ?: return false
allNetworkInfo.forEach { info ->
if (info.state == NetworkInfo.State.CONNECTED) return true
}
}
return false
}
This code is an extension method for Context.
Write down this code at any kotlin file(.kt), then you can use this method in any class which implements Context(such as Activity).