Skip to content

Instantly share code, notes, and snippets.

@AbGhost-cyber
Last active June 12, 2021 13:20
Show Gist options
  • Save AbGhost-cyber/edead4d38559c51d076a4600af5664e0 to your computer and use it in GitHub Desktop.
Save AbGhost-cyber/edead4d38559c51d076a4600af5664e0 to your computer and use it in GitHub Desktop.
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
/**
* Network Utility to detect availability or unavailability of Internet connection
*/
object NetworkUtils : ConnectivityManager.NetworkCallback() {
private val _networkLiveData = MutableLiveData<Events<Boolean>>()
private val networkLiveData: MutableLiveData<Events<Boolean>> = _networkLiveData
/**
* Returns instance of [LiveData] which can be observed for network changes.
*/
fun getNetworkLiveData(context: Context): LiveData<Events<Boolean>> {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(this)
} else {
val builder = NetworkRequest.Builder()
connectivityManager.registerNetworkCallback(builder.build(), this)
}
var isConnected = false
// Retrieve current status of connectivity
connectivityManager.allNetworks.forEach { network ->
val networkCapability = connectivityManager.getNetworkCapabilities(network)
networkCapability?.let {
if (it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
isConnected = true
return@forEach
}
}
}
_networkLiveData.postValue(Events(isConnected))
return networkLiveData
}
override fun onAvailable(network: Network) {
_networkLiveData.postValue(Events(true))
}
override fun onLost(network: Network) {
networkLiveData.postValue(Events(false))
}
}
/* if you wanna observe always, here it is:-
* you might want to observe this in your main activity*/
NetworkUtils.getNetworkLiveData(applicationContext).observe(this, Observer {
it?.let { event ->
val isConnected = event.peekContent()
//you may decide to use peekcontent if not handled
if (isConnected) {
//do something
} else {
//do something else
}
}
})
// how to use in your viewmodel to check for connection?, check below
private fun getConnectionByPeeking(): Boolean {
val events = NetworkUtils.getNetworkLiveData(context.applicationContext).value
events?.let {
return it.peekContent()
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment