Here's a Kotlin implementation where you get to breakdown which transport your device is connect to the network.
Interesting part would be that you can use <ConnectivityManager>
to get from system service without casting it, makes things cleaner.
And, one thing people failed to mention is that connectivityManager?.activeNetwork
is only available for Android Marshmallow and above.
For device lower than that, we can resort to connectivityManager?.activeNetworkInfo
and activeNetworkInfo.isConnected
, even though they are deprecated.
val connectivityManager = context.getSystemService<ConnectivityManager>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val activeNetwork = connectivityManager?.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return when {
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
else -> false
}
} else {
val activeNetworkInfo = connectivityManager?.activeNetworkInfo ?: return false
return activeNetworkInfo.isConnected
}