-
-
Save AafaaqAli/c4fe3f744efd82c12c82c1bcc16bcccc to your computer and use it in GitHub Desktop.
Android Kotlin extension to check network connectivity
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 | |
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