我有
compileSdkVersion 29
和
targetSdkVersion 29
在我的android
应用中。并使用以下代码检查是否存在连接:
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connectivityManager?.activeNetworkInfo?.isConnected ?: false
但是我的targetSdk
已弃用activeNetworkInfo
。如何在不使用不推荐使用的方法和变量的情况下检查连接状态?
答案 0 :(得分:0)
请改用ConnectivityManager.NetworkCallback,这里是link的文档
答案 1 :(得分:0)
您可以按照以下步骤进行操作:
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
val network = connectivityManager.activeNetwork
val capabilities = connectivityManager.getNetworkCapabilities(network)
return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(
NetworkCapabilities.TRANSPORT_CELLULAR
))
}