I call the following function in onCreate and when I turn on and off the network connection on my device while I am on this activity, it shows the message perfectly fine. However, when I open this activity while the network on my device is turned off, it doesn't show the message that the network is turned off whereas when I open the activity when the network is turned on, it shows the message that I am connected to the network.
private fun checkConnection() {
connectivity = CheckConnectivity(application)
connectivity.observe(this, { isConnected ->
if (isConnected) {
Toast.makeText(this,"You are connected to the internet",Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this,"You are NOT connected to the internet",Toast.LENGTH_SHORT).show()
}
})
}
Following is CheckConnectivity.kt
class CheckConnectivity(private val connectivityManager: ConnectivityManager) :
LiveData<Boolean>() {
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) {
super.onAvailable(network)
postValue(true)
}
override fun onLost(network: Network) {
super.onLost(network)
postValue(false)
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onActive() {
super.onActive()
val builder=NetworkRequest.Builder()
connectivityManager.registerNetworkCallback(builder.build(),networkCallback)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onInactive() {
super.onInactive()
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}