Last active
July 24, 2020 13:07
-
-
Save brh/57d211664e686d3dbfa3e2fec1d9e853 to your computer and use it in GitHub Desktop.
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 androidx.lifecycle.LiveData | |
object NetworkDetectorLiveData : LiveData<Boolean>() { | |
private val manager: ConnectivityManager by lazy { | |
ManagementApp.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
} | |
private var connectionCnt = 0 | |
private val netCallback= object: ConnectivityManager.NetworkCallback(){ | |
override fun onAvailable(network: Network) { | |
postValue(true) | |
connectionCnt++ | |
super.onAvailable(network) | |
} | |
override fun onLost(network: Network) { | |
connectionCnt-- | |
if (connectionCnt == 0) { | |
postValue(false) | |
} | |
super.onLost(network) | |
} | |
} | |
override fun onActive() { | |
connectionCnt = 0 | |
val networkRequest = NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) | |
.build() | |
manager.registerNetworkCallback(networkRequest, netCallback) | |
} | |
override fun onInactive() { | |
connectionCnt = 0 | |
manager.unregisterNetworkCallback(netCallback) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment