Created
November 21, 2020 20:03
-
-
Save alifhasnain/3c883e83304dbe8363037b8c1eef64d1 to your computer and use it in GitHub Desktop.
This is a class for observing network state. It was taken Foodium App.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<Boolean> = MutableLiveData() | |
/** | |
* Returns instance of [LiveData] which can be observed for network changes. | |
*/ | |
fun getNetworkLiveData(context: Context): LiveData<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(isConnected) | |
return networkLiveData | |
} | |
override fun onAvailable(network: Network) { | |
networkLiveData.postValue(true) | |
} | |
override fun onLost(network: Network) { | |
networkLiveData.postValue(false) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment