Skip to content

Instantly share code, notes, and snippets.

@alana-mullen
Created January 16, 2020 00:28
Show Gist options
  • Save alana-mullen/0634bf94e2935baf8ad00ba4c6e3e7cb to your computer and use it in GitHub Desktop.
Save alana-mullen/0634bf94e2935baf8ad00ba4c6e3e7cb to your computer and use it in GitHub Desktop.
Android Kotlin extension to check network connectivity
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