Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android 7 ConnectivityManager requestNetwork() behaviour

I am using some code for detecting if mobile data and the cellular network are available as follows:

final ConnectivityManager connection_manager =
                (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

boolean mobileDataEnabled = false;

try {
    Class cmClass = Class.forName(connection_manager.getClass().getName());
    Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
    method.setAccessible(true); // Make the method callable
    // get the setting for "mobile data"
    mobileDataEnabled = (Boolean)method.invoke(connection_manager);
} catch (Exception e) {
}

if(mobileDataEnabled == true) {
    Log.d(TAG, "mobileDataEnabled == true");
} else {
    Log.d(TAG, "mobileDataEnabled == false");
}

NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

connection_manager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback()
{
    @Override
    public void onAvailable(Network network)
    {Log.d(TAG, "requestNetwork onAvailable()");}

    @Override
        public void onCapabilitiesChanged (Network network, NetworkCapabilities networkCapabilities)
        {Log.d(TAG, "requestNetwork onCapabilitiesChanged()");}

    @Override
        public void onLinkPropertiesChanged (Network network, LinkProperties linkProperties)
        {Log.d(TAG, "requestNetwork onLinkPropertiesChanged()");}

    @Override
        public void onLosing (Network network, int maxMsToLive)
        {Log.d(TAG, "requestNetwork onLosing()");}

    @Override
        public void onLost (Network network)
        {Log.d(TAG, "requestNetwork onLost()");}
});

So far this has been working correctly and the onAvailable() callback gets fired if the mobile data can be used. However, I have just tried on an android 7 device and although mobileDataEnabled is being set to true, indicating that the network is available, none of the requestNetwork() callbacks are getting fired.

Does anyone know if anything has changed in android 7 in this area? I would have at least expected one of the callbacks to be called but nothing ever returns.

like image 892
Kebabman Avatar asked Dec 23 '22 19:12

Kebabman


1 Answers

I found the answer.. I just needed to add the NET_CAPABILITY_INTERNET to the request builder like so:

request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
like image 114
Kebabman Avatar answered Jan 13 '23 01:01

Kebabman