Last active
February 12, 2024 02:04
-
-
Save JunJaBoy/981557b5cbe3e7a281106d443b034647 to your computer and use it in GitHub Desktop.
Snippet for checking if the device internet is available in Android
This file contains hidden or 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
/** | |
* copied from jetcaster, android compose samples | |
* https://github.com/android/compose-samples/blob/main/Jetcaster/app/src/main/java/com/example/jetcaster/ui/JetcasterAppState.kt | |
*/ | |
@Suppress("DEPRECATION") | |
fun checkIfOnline(): Boolean { | |
val cm = ContextCompat.getSystemService(context, ConnectivityManager::class.java) | |
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
val capabilities = cm?.getNetworkCapabilities(cm.activeNetwork) ?: return false | |
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && | |
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) | |
} else { | |
cm?.activeNetworkInfo?.isConnectedOrConnecting == true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment