Skip to content

Instantly share code, notes, and snippets.

@AafaaqAli
Forked from alana-mullen/ConnectivityExtension.kt
Created October 10, 2021 12:58
Show Gist options
  • Save AafaaqAli/c4fe3f744efd82c12c82c1bcc16bcccc to your computer and use it in GitHub Desktop.
Save AafaaqAli/c4fe3f744efd82c12c82c1bcc16bcccc to your computer and use it in GitHub Desktop.
Android Kotlin extension to check network connectivity
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
val Context.isConnected: Boolean
get() {
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
val nw = connectivityManager.activeNetwork ?: return false
val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
else -> false
}
}
else -> {
// Use depreciated methods only on older devices
val nwInfo = connectivityManager.activeNetworkInfo ?: return false
nwInfo.isConnected
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment