Created
January 16, 2020 00:28
-
-
Save alana-mullen/0634bf94e2935baf8ad00ba4c6e3e7cb to your computer and use it in GitHub Desktop.
Android Kotlin extension to check network connectivity
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
import android.content.Context | |
import android.net.ConnectivityManager | |
import android.net.NetworkCapabilities | |
import android.os.Build | |
val Context.isConnected: Boolean | |
get() { | |
val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
return when { | |
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> { | |
val nw = connectivityManager.activeNetwork ?: return false | |
val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false | |
when { | |
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
else -> false | |
} | |
} | |
else -> { | |
// Use depreciated methods only on older devices | |
val nwInfo = connectivityManager.activeNetworkInfo ?: return false | |
nwInfo.isConnected | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment