I want to check Internet connection using Network Capabilities but it is giving me this error:
Must be one of: NetworkCapabilities.NET_CAPABILITY_MMS,
NetworkCapabilities.NET_CAPABILITY_SUPL,
NetworkCapabilities.NET_CAPABILITY_DUN,
NetworkCapabilities.NET_CAPABILITY_FOTA,
NetworkCapabilities.NET_CAPABILITY_IMS,
NetworkCapabilities.NET_CAPABILITY_CBS,
NetworkCapabilities.NET_CAPABILITY_WIFI_P2P,
NetworkCapabilities.NET_CAPABILITY_IA,
NetworkCapabilities.NET_CAPABILITY_RCS,
NetworkCapabilities.NET_CAPABILITY_XCAP,
NetworkCapabilities.NET_CAPABILITY_EIMS,
NetworkCapabilities.NET_CAPABILITY_NOT_METERED,
NetworkCapabilities.NET_CAPABILITY_INTERNET,
NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED,
NetworkCapabilities.NET_CAPABILITY_TRUSTED,
NetworkCapabilities.NET_CAPABILITY_NOT_VPN,
NetworkCapabilities.NET_CAPABILITY_VALIDATED,
NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL,
NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
NetworkCapabilities.NET_CAPABILITY_FOREGROUND,
NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED,
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED, NetworkCapab…
[truncated]
My code:
fun checkInternetConnection(context : Context) : Boolean{
val connectivityManager = context.getSystemService(
Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork?: return false
val activeNetwork = connectivityManager.getNetworkCapabilities(network)?: return false
return when{
activeNetwork.hasCapability(NetworkCapabilities.TRANSPORT_WIFI) -> true
activeNetwork.hasCapability(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
activeNetwork.hasCapability(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
}
I tried to fix it with Android Studio’s auto-correction, but instead of writing the control code I wanted, it changed it with a different code.
2
Answers
I use this to check if device indeed has connection
it works for me, you can try it.
in manifest
in Code
//return boolean value if network available