gpt4 book ai didi

java - activeNetworkInfo 的 Getter 已弃用,在 Java 中已弃用

转载 作者:行者123 更新时间:2023-12-01 17:44:50 25 4
gpt4 key购买 nike

activeNetworkInfo 的 Getter 已弃用,在 Java 中已弃用。如何解决这个问题?

我使用了下面的代码,但 android studio 告诉我“activeNetworkInfo”已被弃用。

应用 list :

minSdkVersion 21
targetSdkVersion 29

@Provides
@Singleton
fun provideIsNetworkAvailable(application: Application): Boolean {
var isConnected = false
val connectivityManager = application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
isConnected = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
isConnected = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return isConnected
}

最佳答案

我正在使用此代码:

private fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}

}
}
}

return result
}

您可以查看下面的地址以获取详细信息。

activeNetworkInfo.type is deprecated in API level 28

关于java - activeNetworkInfo 的 Getter 已弃用,在 Java 中已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60880945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com