gpt4 book ai didi

android - Kotlin:如果网络断开连接,使用 ConnectivityManager 检查网络状态将返回 null。怎么来的?

转载 作者:太空狗 更新时间:2023-10-29 15:35:35 27 4
gpt4 key购买 nike

我尝试使用此功能检查我的网络状态(连接或断开连接):

// Check Network status
private fun isNetworkAvailable(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
return if (connectivityManager is ConnectivityManager) {
val networkInfo = connectivityManager.activeNetworkInfo
networkInfo.isConnected
}
else false
}

这给了我一个java.lang.IllegalStateException: networkInfo 不能为 null - 错误在断开网络的情况下运行时。为什么?我该如何解决这个问题?

最佳答案

根据docs activeNetworkInfo 可能为空:

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

为了确保它不会崩溃,只需使用这个:

 private fun isNetworkAvailable(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
return if (connectivityManager is ConnectivityManager) {
val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
networkInfo?.isConnected ?: false
} else false
}

关于android - Kotlin:如果网络断开连接,使用 ConnectivityManager 检查网络状态将返回 null。怎么来的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49819923/

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