javaandroidkotlinnetwork-programmingandroid-connectivitymanager

Difference between registerDefaultNetworkCallback and registerNetworkCallback


I came across registerDefaultNetworkCallback and registerNetworkCallback while updating my Android app for API 28.

Having reviewed the documentation, I cannot find the difference between registering a network callback and registering a default network callback.

When will one use which?

Thanks in advance :)


Solution

  • As far as I understood, the difference between registerDefaultNetworkCallback and registerNetworkCallback it's only based on customisation.
    registerDefaultNetworkCallback works (surprisingly) as a default network listener, while registerNetworkCallback it's more configurable. For example:

        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
        val builder = NetworkRequest.Builder()
        builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
    
        val networkRequest = builder.build()
        connectivityManager.registerNetworkCallback(networkRequest, 
        object : ConnectivityManager.NetworkCallback () {
            override fun onAvailable(network: Network?) {
                super.onAvailable(network)
                Log.i("Test", "Network Available")
            }
    
            override fun onLost(network: Network?) {
                super.onLost(network)
                Log.i("Test", "Connection lost")
            }
        })
    

    Here onAvailable will be called only if the user connects to a cellular network (by connecting to WiFi it won't log anything). The same does onLost when disconnecting from cellular network.

    If we do it like this:

        connectivityManager.registerDefaultNetworkCallback(object  : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network?) {
                super.onAvailable(network)
                Log.i("Test", "Default -> Network Available")
            }
    
            override fun onLost(network: Network?) {
                super.onLost(network)
                Log.i("Test", "Default -> Connection lost")
            }
        })
    

    Both functions work as default callbacks when the user is connecting (or disconnecting) to/from a network (it can be either WiFi or cellular).

    These are just some very basic examples. Of course NetworkRequest can have a lot of configurations by setting its capability or transportType. You can read more about these in the official documentation of NetworkRequest.