API已弃用NetworkInfo

时间:2019-07-31 06:31:48

标签: android kotlin deprecated networkinfo

我想检查网络连接。因此,我使用了ConnectivityManager.activateNetworkInfo.isConnected

不幸的是,API 29中已弃用该方法。

private fun isOnline(): Boolean {
    val connectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = connectivityManager.activeNetworkInfo
    return networkInfo != null && networkInfo.isConnected
}

,您可以在此处看到折旧消息

enter image description here

1 个答案:

答案 0 :(得分:2)

基于Google Document

  • getActiveNetworkInfo已在API 29上弃用。
  • getAllNetworkInfo已在API 23上弃用。

因此,如果要查找网络连接状态,可以使用此代码。

private fun checkNetworkState(context: Context): Boolean {
    val connectivityManager = context.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
    }
}