Check for internet connectivity on API29

Lorano Denka :

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.

Smashing :

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
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147248&siteId=1