Home > Enterprise >  onLost in NetworkCallback doesn't work when I launch the app
onLost in NetworkCallback doesn't work when I launch the app

Time:12-13

It works when I turn off the internet in the app but it doesn't work when I launch the app without the internet

private val networkCallback: ConnectivityManager.NetworkCallback =
    object: ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            //setButtonEnabled(true)
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            //setButtonEnabled(false)
        }
        

    }

CodePudding user response:

That's because NetworkCallback according to the network change to give you a callback.

the class document says as follows:

Base class for NetworkRequest callbacks. Used for notifications about network changes

if you want to check if the network is available you can use the following code

    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
    val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true

  • Related