Monitoring device connection to the internet on android
When building android applications we sometimes want to make sure that the user is connected to a valid network, this can be challenging when working with the basic network checking techniques. Sometimes the user is connected to a valid network but the network lacks connection to the internet, this is what we'll be fixing today.
I created a gist on github with the code required to sort this problem out. Once you add the code to your utilities directory, you can observe the device's internet connection from any composable or fragment.
Here's how you'd go about observing the network's internet connection
import com.example.android.core.utilities.InternetConnectionLiveData
// this var has to be lateinit bc the networkCallback and the connectivityManager
// can only be used once the onCreate has been called
private lateinit var internetConnectionLiveData: InternetConnectionLiveData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
internetConnectionLiveData = InternetConnectionLiveData(requireContext())
}
// observe wherever possible
internetConnectionLiveData.observe(viewLifecycleOwner){ hasInternet ->
viewModel.updateHasInternetStatus(hasInternet)
}
The code snippet above can be used to observe an available network's connection and you can ensure the user is connected and if they're not you can inform them of this through a Toast or Snackbar.
That's it! Add a comment on the gist if you've got any questions or ideas on how to optimize it.