Last active
July 24, 2021 10:25
-
-
Save Turskyi/56f375d6a3812719507288700370f1e8 to your computer and use it in GitHub Desktop.
Convenient extensions for Fragments in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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