Skip to content

Instantly share code, notes, and snippets.

@JunJaBoy
Last active February 12, 2024 02:04
Show Gist options
  • Save JunJaBoy/981557b5cbe3e7a281106d443b034647 to your computer and use it in GitHub Desktop.
Save JunJaBoy/981557b5cbe3e7a281106d443b034647 to your computer and use it in GitHub Desktop.
Snippet for checking if the device internet is available in Android
/**
* 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