Search code examples
androidkotlinandroid-connectivitymanager

Listening to network changes using Connectivity Manager


I am trying to listen to network changes using method registerDefaultNetworkCallback() of conenctivityManager Using the code below from this answer

     val connectivityManager = cotnext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager?.let {
            it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    //take action when network connection is gained
                }
                override fun onLost(network: Network) {
                    //take action when network connection is lost
                }
            })
        }

but I have a few questions about this method:

  1. what if the phone is connected to wifi but the wifi is not connected to Internet
  2. In the method documentation I read this which I don't understand, when exactly will the limit will hit? If the callback is called 100 times then an Exception will be thrown? And how to handle this?

To avoid performance issues due to apps leaking callbacks, the system will limit the number of outstanding requests to 100 per app (identified by their UID), shared with all variants of this method, of requestNetwork as well as ConnectivityDiagnosticsManager.registerConnectivityDiagnosticsCallback. Requesting a network with this method will count toward this limit. If this limit is exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources, make sure to unregister the callbacks with unregisterNetworkCallback(ConnectivityManager.NetworkCallback).


Solution

    1. what if the phone is connected to wifi but the wifi is not connected to Internet

    The answer, this method will return false

    1. In the method documentation I read this which I don't understand, when exactly will the limit will hit? If the callback is called 100 times then an Exception will be thrown? And how to handle this?

    I think it means if you cant register more than 100 callback