What is alternative to ConnectivityManager.TYPE_WIFI deprecated in Android P API 28?
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));
}
ConnectivityManager.TYPE_WIFI
is Deprecated. You should use NetworkCapabilities
.
This replaces the old ConnectivityManager.TYPE_MOBILE
method of network selection. Rather than indicate a need for Wi-Fi because an application needs high bandwidth and risk obsolescence when a new, fast network appears (like LTE), the application should specify it needs high bandwidth. Similarly if an application needs an unmetered network for a bulk transfer it can specify that rather than assuming all cellular based connections are metered and all Wi-Fi based connections are not.
Applications should instead use
NetworkCapabilities.hasTransport(int)
orrequestNetwork(NetworkRequest, NetworkCallback)
to request an appropriate network. for supported transports.
You can try this way
NetworkAgentInfo networkAgent;
int type = ConnectivityManager.TYPE_NONE;
if (networkAgent.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
type = ConnectivityManager.TYPE_MOBILE;
} else if (networkAgent.networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI)) {
type = ConnectivityManager.TYPE_WIFI;
}
Use below method.. 19/06/2019
public boolean isconnectedToWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo == null) {
return false;
}
return networkInfo.isConnected();
}
}