Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check the android device has internet connectivity or not. It ensure that it will be supported in all API levels or android versions. Using Kotlin
object NetworkUtils {
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
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
networkLiveData.postValue(true)
}
override fun onLost(network: Network?) {
networkLiveData.postValue(false)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
} else {
val builder = NetworkRequest.Builder()
connectivityManager.registerNetworkCallback(builder.build(), networkCallback)
}
val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true
networkLiveData.postValue(isConnected)
return networkLiveData
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment