gpt4 book ai didi

android - 连接 VPN 时缺少 ConnectivityManager

转载 作者:行者123 更新时间:2023-12-04 23:49:57 25 4
gpt4 key购买 nike

我有一个返回设备连接状态的功能,它一直工作正常,除非设备连接到 VPN,当网络不可用时它会给出误报


fun isConnected(): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true

else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
ConnectivityManager.TYPE_VPN -> true
else -> false
}

}
}
}
return result
}

最佳答案

如果你想确认你的网络有internet,你不能只测试connectivityManager.activeNetworkactNw.hasTransport .connectivityManager.activeNetwork将返回 VPN,因为它是 Activity 网络,无论它是否有互联网。 actNw.hasTransport只是让您知道连接的传输。如果您不关心传输,您可能可以完全删除该代码。
你应该检查的是NET_CAPABILITY_INTERNETNET_CAPABILITY_VALIDATED .
NET_CAPABILITY_INTERNET

Indicates that this network should be able to reach the internet.


NET_CAPABILITY_VALIDATED

Indicates that connectivity on this network was successfullyvalidated. For example, for a network with NET_CAPABILITY_INTERNET, itmeans that Internet connectivity was successfully detected.


因此,您真正需要的是检查 Activity 网络是否具有这两种功能,以确定您是否连接到具有互联网连接的网络。
actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);

关于android - 连接 VPN 时缺少 ConnectivityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66350798/

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