Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for internet connectivity on API29

Tags:

java

android

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.


1 Answers

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
    }
}
like image 52
Smashing Avatar answered Mar 24 '26 09:03

Smashing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!