-
-
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.
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
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