Wednesday, 19 September 2018

ConnectionManager not giving network callbacks when using `TRANSPORT_CELLULAR`

I'm trying to receive callbacks whenever the phone's cellular data connection changes. I essentially need to know when it turns off and when it turns on.

I used to do this with the TelephonyManager and PhoneStateListener.LISTEN_SERVICE_STATE, but now I want to use the ConnectionManager with registerNetworkCallback.

The following code sample has been tried on an Android Emulator (API 28), A HUAWEI P20 Lite (API 26), an HTC One M8 (API 23), and a Motorola G6 (API 26). None of them call any callbacks when I switch mobile data on/off, or activate airplane mode.

People say this should work.

    NetworkRequest.Builder builder = new NetworkRequest.Builder();

    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

    connManager.registerNetworkCallback(builder.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            Log.d("Conman Test", "onAvailable");
        }

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

        @Override
        public void onUnavailable() {
            Log.d("Conman Test", "onUnavailable");
        }

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

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

I have tried NetworkCapabilities.TRANSPORT_WIFI, and it works fine on all the devices. So why not NetworkCapabilities.TRANSPORT_CELLULAR?



from ConnectionManager not giving network callbacks when using `TRANSPORT_CELLULAR`

No comments:

Post a Comment