0

I have created an extension function for kotlin that detects me if I am connected to the Internet but these methods put me that they are deprecated, what methods I could use instead, I leave you the function I have:

    fun Context.isInternetAvailable(): Boolean {
    val connectivityManager =
        this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val nw = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
        return when {
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            else -> false
        }
    } else {
        val nwInfo = connectivityManager.activeNetworkInfo ?: return false
        return nwInfo.isConnected
    }
}
Ludiras
  • 338
  • 3
  • 20

2 Answers2

0

In my opinion that's better you use http client libraries such as Retrofit or Ktor and catch exception of network per request.

ImanX
  • 789
  • 6
  • 23
0

You can use this , its works fine in

kotlin

 @RequiresApi(Build.VERSION_CODES.M)
    fun Context.isInternetAvailable() : Boolean{

        val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = connectivityManager.activeNetwork
        val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork)

        return networkCapabilities!= null && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET

    }
aksBD
  • 189
  • 1
  • 6