nameisjayant / Check-Network-Connectivity-with-LiveData-Android-kotlin

so In this project we will check our application is connected with internet or not through Live data , if the application is connected with Internet , we will update the textview with "connect with internet" or if it's not connected we will update with No Network
18 stars 1 forks source link

Not Working when network is off initially. #1

Open milon27 opened 3 years ago

milon27 commented 3 years ago

when you have an internet connection and you launch the app. it's showing connected with the internet. but when you turn off all networks and lanch the app again it's showing noting. the network callback did not trigger at all until you again turn on the wifi/internet.

hope fully you will reply.

waulite-786 commented 2 years ago

User like this then it will work

class ConnectivityLiveData(private val connectivityManager: ConnectivityManager) : LiveData() { private val tag = ConnectivityLiveData::class.java.name private var active:Boolean = false private var onAvailable:Boolean = false private var lost:Boolean = false private var inactive:Boolean = false

constructor(application: Application) : this(application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)

private val networkCallback= @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
        Log.e(tag,"onAvailable()")
        onAvailable = true
        super.onAvailable(network)
        setValueInLiveData()
    }

    override fun onLost(network: Network) {
        Log.e(tag,"onLost()")
        lost = true
        super.onLost(network)
        setValueInLiveData()
    }
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onActive() {
    Log.e(tag,"onActive()")
    active = true
    super.onActive()
    val builder=NetworkRequest.Builder()
    connectivityManager.registerNetworkCallback(builder.build(),networkCallback)
    setValueInLiveData()
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onInactive() {
    Log.e(tag,"onInactive()")
    inactive = true;
    super.onInactive()
    connectivityManager.unregisterNetworkCallback(networkCallback)
    setValueInLiveData()
}

private fun setValueInLiveData(){ if(active && onAvailable){ postValue(true) setFalse() } if(active){ postValue(false) setFalse() } if(onAvailable){ postValue(true) setFalse() } if(lost){ postValue(false) setFalse() } }

private fun setFalse(){
    active = false
    onAvailable = false
    lost = false
    inactive = false
}

}

Micoder-dev commented 2 years ago

@waulite-786 replace this with ==> LiveData() <== with ==> LiveData()

a bit of mistake but its working fine :-)