Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Last active July 24, 2021 10:25
Show Gist options
  • Save Turskyi/56f375d6a3812719507288700370f1e8 to your computer and use it in GitHub Desktop.
Save Turskyi/56f375d6a3812719507288700370f1e8 to your computer and use it in GitHub Desktop.
Convenient extensions for Fragments in Kotlin
/**
* @Description
* Checks if device is online or not
*/
fun Fragment.isOnline(): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val connectivityManager =
this.activity?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork
return if (network != null) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)!!
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
)
} else false
} else {
/* Initial Value */
var isConnected: Boolean? = false
val connectivityManager =
this.activity?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@Suppress("DEPRECATION") val activeNetwork = connectivityManager.activeNetworkInfo
@Suppress("DEPRECATION")
if (activeNetwork != null && activeNetwork.isConnected) {
isConnected = true
}
return isConnected ?: false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment