0

我有

compileSdkVersion 29

targetSdkVersion 29

在我的android应用程序中。为了检查是否存在连接,我使用下一个代码:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connectivityManager?.activeNetworkInfo?.isConnected ?: false

但是我targetSdk的 theactiveNetworkInfo已被弃用。如何在没有弃用方法和变量的情况下检查连接状态?

4

2 回答 2

1

你可以这样做:

    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
        ))
    }
于 2019-09-12T11:11:44.957 回答
0

改用 ConnectivityManager.NetworkCallback,这里是文档的链接

于 2019-09-12T10:43:10.603 回答