Last active
September 24, 2021 18:47
-
-
Save ShivamKumarJha/1d80452346e25ad5c4e7eca6d87c9d1b to your computer and use it in GitHub Desktop.
Check internet using ConnectivityManager. Supports API 16 and above.
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.net.ConnectivityManager | |
import android.net.NetworkCapabilities | |
import android.os.Build | |
class NetworkHelper(private val connectivityManager: ConnectivityManager) { | |
fun isNetworkConnected(): Boolean { | |
var result = false | |
when { | |
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> { | |
val networkCapabilities = connectivityManager.activeNetwork ?: return false | |
val activeNetwork = | |
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false | |
result = when { | |
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true | |
else -> false | |
} | |
} | |
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> { | |
connectivityManager.run { | |
connectivityManager.activeNetworkInfo?.run { | |
result = when (type) { | |
ConnectivityManager.TYPE_WIFI -> true | |
ConnectivityManager.TYPE_MOBILE -> true | |
ConnectivityManager.TYPE_ETHERNET -> true | |
else -> false | |
} | |
} | |
} | |
} | |
else -> { | |
val networkInfo = connectivityManager.activeNetworkInfo | |
result = networkInfo != null && networkInfo.isConnected | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment