-
-
Save grrigore/bf2e5993a98b7afb17e331eee8a6f5b9 to your computer and use it in GitHub Desktop.
ConnectivityMonitor.kt
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.net.ConnectivityManager | |
import android.net.Network | |
import android.net.NetworkCapabilities | |
import android.net.NetworkRequest | |
import androidx.lifecycle.* | |
import java.io.IOException | |
import java.net.InetAddress | |
class ConnectivityMonitor( | |
private val connectivityManager: ConnectivityManager, | |
lifecycle: Lifecycle, | |
) : LifecycleObserver { | |
init { | |
lifecycle.addObserver(this) | |
} | |
private var isActive = false | |
private val status = MutableLiveData<Boolean>() | |
val connectedStatus: LiveData<Boolean> | |
get() = status | |
private val connectivityCallback = object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
status.postValue( | |
try { | |
val googleDnsName = "8.8.8.8" | |
val timeout = 1000 | |
InetAddress.getByName(googleDnsName).isReachable(timeout) | |
true | |
} catch (e: IOException) { | |
false | |
} | |
) | |
} | |
override fun onLost(network: Network) { | |
status.postValue(false) | |
} | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) | |
fun stop() { | |
if (isActive) { | |
connectivityManager.unregisterNetworkCallback(connectivityCallback) | |
isActive = false | |
} | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) | |
fun start() { | |
if (!isActive) { | |
// we don't have internet connection, so we listen to notifications in connection status | |
connectivityManager.registerNetworkCallback( | |
NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), | |
connectivityCallback | |
) | |
isActive = true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment