Created
August 10, 2020 17:45
-
-
Save Skyyo/07e4a2f072d41fd6337ddf2404b5c8cd to your computer and use it in GitHub Desktop.
Tracker for internet connection updates. #network_connection
This file contains hidden or 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
object NetworkUtils : ConnectivityManager.NetworkCallback() { | |
private val networkLiveData: MutableLiveData<Boolean> = MutableLiveData() | |
override fun onAvailable(network: Network) { | |
networkLiveData.postValue(true) | |
} | |
override fun onLost(network: Network) { | |
networkLiveData.postValue(false) | |
} | |
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 for the first observer | |
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment