Created
July 16, 2020 05:22
-
-
Save peterpazmandi/02f6906e6234cd043fcde0e91bac8ecd to your computer and use it in GitHub Desktop.
Network Utility to detect availability or unavailability of Internet 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
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