Created
September 5, 2020 22:40
-
-
Save philipplackner/6b1cb87badadb5ae1f2aeac749f7cba7 to your computer and use it in GitHub Desktop.
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
import android.content.Context | |
import android.net.ConnectivityManager | |
import android.net.NetworkCapabilities | |
import android.os.Build | |
fun hasInternetConnection(context: Context): Boolean { | |
val connectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
val activeNetwork = connectivityManager.activeNetwork ?: return false | |
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false | |
return when { | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true | |
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true | |
else -> false | |
} | |
} else { | |
return connectivityManager.activeNetworkInfo?.isAvailable ?: false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment