Kotlin - Network connection validation

697 views Asked by At

How do i check if there is a network connection in my app? (Language used is kotlin)

Most methods already described in StackOverflow and in the web generally are already deprecated. We can't just check if it's null. Also can't just check if there is a wifi or cellular data or BT or ethernet connection available and expect that to be enough. What if the network connection is available but the network is "EDGE", or what if the network is available but suddenly lost, or what if the network is available but it can't ping because of an unknown issue ? The best way is then to check if it can actually ping. But we don't need to start sending a ping in our app, our smartphones already do that in the framework. Google already took care of that since ages. So up to now nobody answered 100% correct how to actually handle this situation.

Below then is how i do it:

    private fun android.content.Context.isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val nw = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
        return when {
            actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
                    actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) &&
                    actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED) &&
                    (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                            actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                            actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                            actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) -> true
            else -> false
        }
    }

explanation:

  1. "android.content.Context" used so that i do not need to import it since i used it just once. You could use Context and just import it if there are multiple uses of it.
  2. we define (lines 2,3,4)
  3. we check NET_CAPABILITY_INTERNET
  4. we check NET_CAPABILITY_VALIDATED
  5. we check NET_CAPABILITY_NOT_SUSPENDED
  6. if the above are true and there is a network connection (it's always good to double check something), then return true. Else false.

That's how we check 100% if there is connectivity. We can't just rely on a null state check or a network state indicating that we have a network.

0

There are 0 answers