[英]NetWorkInfo, connectivityManager.ActiveNetworkInfo, and .IsConnected are obsolete
I have an app that is targeting Android 8.0 (API Level 26 - Oreo) through Android 10.0 (API Level 29 - Q) and the following code is depreciated:我有一个面向 Android 8.0(API 级别 26 - Oreo)到 Android 10.0(API 级别 29 - Q)的应用程序,以下代码已弃用:
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
If NetworkInfo
and anything associated with it is depreciated, what do I use in it's place.如果
NetworkInfo
和与之相关的任何东西都贬值了,我在它的位置使用什么。 I've researched this issue all day and EVERY suggestion I've seen uses functionality that is depreciated (and written in java which is a total mystery to me).我一整天都在研究这个问题,我看到的每一个建议都使用了折旧的功能(用 java 编写,这对我来说是个谜)。 So please don't tell me this is a duplicated of some issue already posted somewhere, it's not.
所以请不要告诉我这是一个已经在某处发布的问题的重复,它不是。 Also, if you provide code, please c#.
另外,如果您提供代码,请使用 c#。
Although the code is in Kotlin, I hope you will understand whats the alternative.虽然代码在 Kotlin 中,但我希望你能理解什么是替代方案。
fun isConnectedToTheInternet(): Boolean {
val cm = application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
return when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
}
} else {
cm.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
return true
} else if (type == ConnectivityManager.TYPE_MOBILE) {
return true
}
}
}
}
return false
}
If it can help you or if someone can convert this code to C#.如果它可以帮助您,或者是否有人可以将此代码转换为 C#。
This code is functional in Kotlin and is not depreciated .这段代码在 Kotlin 中是有效的,并且没有折旧。
private fun isInternetConnection(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capability = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return capability?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
}
Hoping to have helped you希望能帮到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.