I use the following method for checking the internet connectivity:
public boolean isInternetConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
Though, I have discovered that NetworkInfo, getActiveNetworkInfo(), and isConnected() are all now deprecated. I have checked several threads on SO:
ConnectivityManager getNetworkInfo(int) deprecated
activeNetworkInfo.type is deprecated in API level 28
Though, they all offer answers with deprecated methods. I have been looking around without any luck. Is there any simple way to check for internet connectivity or should I continue using my method and disregard the deprecated since it works up to API29?
Thank you.
Have a look at .hasTransport
val networkAvailability = cm.getNetworkCapabilities(cm.activeNetwork)
if(networkAvailability !=null && networkAvailability.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkAvailability.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))
{
//has network
if (networkAvailability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //wifi
} else if (networkAvailability.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { //cellular
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With