-
-
Save sagar-viradiya/18ec984f6bea85337eab1770900c65aa to your computer and use it in GitHub Desktop.
DevFest India 2020 Day 2 - NetworkHelper.kt
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
import android.content.Context | |
import android.net.ConnectivityManager | |
import android.net.NetworkCapabilities | |
import android.os.Build | |
class NetworkHelper(private val context: Context) { | |
fun isNetworkConnected(): Boolean { | |
var isNetworkConnected = false | |
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 | |
isNetworkConnected = when { | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true | |
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true | |
else -> false | |
} | |
} else { | |
connectivityManager.run { | |
connectivityManager.activeNetworkInfo?.run { | |
isNetworkConnected = isConnected | |
} | |
} | |
} | |
return isNetworkConnected | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kotlin will be used