Skip to content

Instantly share code, notes, and snippets.

@ziyaddinovchiyev
Created November 15, 2021 09:47
Show Gist options
  • Save ziyaddinovchiyev/eedc1c5d6a7cd9494a054e755bd75dc2 to your computer and use it in GitHub Desktop.
Save ziyaddinovchiyev/eedc1c5d6a7cd9494a054e755bd75dc2 to your computer and use it in GitHub Desktop.
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
class ConnectionLiveData(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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment