Skip to content

Instantly share code, notes, and snippets.

@sfunke
Forked from Farbklex/ConnectivityChecker.kt
Created February 14, 2022 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfunke/40e61445b7046dae5bfb8460616458b8 to your computer and use it in GitHub Desktop.
Save sfunke/40e61445b7046dae5bfb8460616458b8 to your computer and use it in GitHub Desktop.
Android: Check if the device has internet access on devices with API level >= 23.
package me.a_hoffmann.gists
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
/**
* Checks if the device has an internet connection.
* NOTE: Works only on android API level 23 and above!
*/
class ConnectivityChecker(private val context: Context){
/**
* Check if the device has an internet connection.
*
* @return True if the device is connected to a network which also gives it access to the internet.
* False otherwise.
*/
fun isInternetAvailable(): Boolean {
val connectivityManager = context.getSystemService(
Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
?: return false
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
// If we check only for "NET_CAPABILITY_INTERNET", we get "true" if we are connected to a wifi
// which has no access to the internet. "NET_CAPABILITY_VALIDATED" also verifies that we
// are online
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment