Skip to content

Instantly share code, notes, and snippets.

@mbobiosio
Created August 18, 2020 08:28
Show Gist options
  • Save mbobiosio/9d873c5c881747d57ab94d98c45e1e86 to your computer and use it in GitHub Desktop.
Save mbobiosio/9d873c5c881747d57ab94d98c45e1e86 to your computer and use it in GitHub Desktop.
object NetworkUtil {
fun isNetworkAvailable(context: Context?): Boolean {
if (context == null) return false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
return true
}
}
}
} else {
try {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
} catch (e: Exception) {
//
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment