Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NetworkCapabilities object on Android?

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?

like image 314
ashishb Avatar asked Mar 24 '15 02:03

ashishb


People also ask

What is Connectivity Manager in Android?

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.

How can you instantiate the object of Connectivity Manager?

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.

What is Networkcapabilities?

Definition. Network capabilities refer to short-term authorizations that a sender obtains from a receiver and stamps on its packets to the receiver.


2 Answers

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.

like image 136
Satty Avatar answered Oct 21 '22 07:10

Satty


    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()

like image 32
Luca Biasotto Avatar answered Oct 21 '22 09:10

Luca Biasotto