What is alternative to ConnectivityManager.TYPE_WIFI deprecated in Android P API 28?

Amrut picture Amrut · Oct 15, 2018 · Viewed 10.1k times · Source

ConnectivityManager.TYPE_WIFI is deprecated in Android P API 28. Also, NetworkInfo#getType and ConnectivityManager.TYPE_MOBILE's are also deprecated.

So, what are the alternatives for them? I understood that the we've to use the method from NetworkCapabilities class. However I'm not able to merge all the things in one place like how to do getType() in NetworkCapabilities class and how to add the WIFI and cellular data checks on it?

Please assist.

Answer

Chintan Soni picture Chintan Soni · Oct 15, 2018

You can use below snippet to check if you have Wifi connection or Cellular:

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    Network network = connectivityManager.getActiveNetwork();
    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
    return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
}