Last active
March 30, 2024 12:56
-
-
Save VahidHoseini-ir/7b6e012b38e3be9b75f590cfe3751a23 to your computer and use it in GitHub Desktop.
how to check network connectivity in Kotlin
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
fun isNetworkConnected(context: Context): Boolean { | |
val connectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
val network = connectivityManager.activeNetwork ?: return false | |
val networkCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return false | |
return when { | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true | |
else -> false | |
} | |
} else { | |
val networkInfo = connectivityManager.activeNetworkInfo | |
return networkInfo != null && networkInfo.isConnected | |
} | |
} |
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
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
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
if (isNetworkConnected(this)) { | |
// Network is connected | |
// Your code here | |
} else { | |
// Network is not connected | |
// Your code here | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment