How to get android.net.NetworkCapabilities
on Android?
I looked at https://developer.android.com/reference/android/net/ConnectivityManager.html and did not find any way to get NetworkCapabilities
object.
Any suggestions on how to get it?
The ConnectivityManager provides an API that enables you to request that the device connect to a network based on various conditions that include device capabilities and data transport options.
getSystemService(Context. CONNECTIVITY_SERVICE); Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo.
Definition. Network capabilities refer to short-term authorizations that a sender obtains from a receiver and stamps on its packets to the receiver.
ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connectivity.getAllNetworks();
for (int i = 0; i < networks.length; i++) {
NetworkCapabilities capabilities = connectivity.getNetworkCapabilities(networks[i]);
}
But this is available with API 21 and above.
NetworkCapabilities nc = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null) {
nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
}
}else{
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connectivity.getAllNetworks();
for (int i = 0; i < networks.length && nc == null; i++) {
nc = connectivity.getNetworkCapabilities(networks[i]);
}
}
// use now nc
On Android > 23 you can use ConnectivityManager
and getActiveNetwork()
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