Android getAllNetworkInfo() is Deprecated. What is the alternative?

后端 未结 6 1512
生来不讨喜
生来不讨喜 2021-01-31 09:33

I want to use the ConnectivityManager which provides the getAllNetworkInfo() method for checking the availability of network in Android. This method wa

6条回答
  •  旧时难觅i
    2021-01-31 09:35

    For someone needs Kotlin version, (Below is same code with Maor Hadad's)

    fun Context.isNetworkConnected(): Boolean {
      val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        val allNetworks = manager?.allNetworks?.let { it } ?: return false
        allNetworks.forEach { network ->
          val info = manager.getNetworkInfo(network)
          if (info.state == NetworkInfo.State.CONNECTED) return true
        }
      } else {
        val allNetworkInfo = manager?.allNetworkInfo?.let { it } ?: return false
        allNetworkInfo.forEach { info ->
          if (info.state == NetworkInfo.State.CONNECTED) return true
        }
      }
      return false
    }
    

    This code is an extension method for Context.

    Write down this code at any kotlin file(.kt), then you can use this method in any class which implements Context(such as Activity).

提交回复
热议问题