Created
March 30, 2024 12:59
-
-
Save VahidHoseini-ir/5b58199d764e5a95a76908bb7bf482d0 to your computer and use it in GitHub Desktop.
Check NetworkConnectivity in JAVA
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
public static boolean isNetworkConnected(Context context) { | |
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
android.net.Network network = connectivityManager.getActiveNetwork(); | |
if (network == null) return false; | |
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network); | |
if (networkCapabilities == null) return false; | |
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { | |
return true; | |
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { | |
return true; | |
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) { | |
return true; | |
} | |
return false; | |
} else { | |
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |
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(context)) { | |
// 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