问题
I want to remove the warning which is showing in the code below m version.I had use below code which is working good but still want to remove the warning which is showing in line ConnectivityManager.TYPE_WIFI.Can below warning be removed which is also showing in kotlin compiler ??
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true
} else if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true
}
}
}
} else {
cm?.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
return true
} else if (type == ConnectivityManager.TYPE_MOBILE) {
return true
}
}
}
}
Warning :- 'getter for type: Int' is deprecated.
回答1:
Try this
You can use @Suppress("DEPRECATION")
to remove that warning
SAMPLE CODE
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val networkResult = getConnectionType(this)
}
@Suppress("DEPRECATION")
fun getConnectionType(context: Context): Boolean {
var result = false
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true
} else if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true
}
}
}
} else {
cm?.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
result = true
} else if (type == ConnectivityManager.TYPE_MOBILE) {
result = true
}
}
}
}
return result
}
}
CHECK THE SCREENSHOT
来源:https://stackoverflow.com/questions/56353916/connectivitymanager-type-wifi-is-showing-deprecated-in-code-i-had-use-network-ca