Not Working when network is off initially.
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.
User like this then it will work
class ConnectivityLiveData(private val connectivityManager: ConnectivityManager) : LiveData<Boolean>() { 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
}
}
@waulite-786 replace this with ==> LiveData() <== with ==> LiveData<Boolean>()
a bit of mistake but its working fine :-)