Skip to content

Instantly share code, notes, and snippets.

@giovanileitevitor
Created February 16, 2023 14:51
Show Gist options
  • Save giovanileitevitor/8c14b9e60b14e2403b1d1a08e781b0a2 to your computer and use it in GitHub Desktop.
Save giovanileitevitor/8c14b9e60b14e2403b1d1a08e781b0a2 to your computer and use it in GitHub Desktop.
Get Internet connection type status
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 {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment