Sasha Arutyunyan
Sasha Arutyunyan

Reputation: 105

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

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)
        }
        

    }

Upvotes: 2

Views: 1660

Answers (2)

Shayla Sawchenko
Shayla Sawchenko

Reputation: 681

I am seeing the same thing. If I launch the app without a network connection neither NetworkCallback.onLost or NetworkCallback.onUnavailable are called. Yet if I launch the app with a network connection, NetworkCallback.onAvailable is called.

Seems like a ConnectivityManager bug to me honestly. I added a work around that checks if the activeNetwork is null at the time I setup the callback, and if it is, I just run the logic that I normally would if the callback told me the network is unavailable. This seems to handle it for me.

val callback = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
        // Run my onAvailable code
    }

    override fun onLost(network: Network) {
        // Run my onLost code
    }

    override fun onUnavailable() {
        // Run my onUnavailable code
    }
}
connectivityManager.registerDefaultNetworkCallback(callback)

// !!! Added this !!!
// There appears to be an issue where neither NetworkCallback.onLost or NetworkCallback.onUnavailable
// are called if the app is started without a network connection; because of this we cannot
// rely on the callback correctly initializing if offline. Work around here 
// by checking activeNetwork immediately.
if (connectivityManager.activeNetwork == null) {
    // Run my onUnavailable code
}

Upvotes: 5

Lenoarod
Lenoarod

Reputation: 3610

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

Upvotes: 3

Related Questions