连接 VPN 时缺少 ConnectivityManager

ConnectivityManager missing when a VPN is connected

我有一个 returns 设备连接状态的功能,它一直工作正常,除了当设备连接到 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
    }

你试过添加这个吗:

actNw.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true

如果你想确认你的网络是否可以上网,你不能只测试connectivityManager.activeNetworkactNw.hasTransport

connectivityManager.activeNetwork 将 return VPN,因为无论是否有互联网,它都是活动网络。 actNw.hasTransport 只是让你知道连接的传输。如果您不关心传输,您可以完全删除该代码。

您应该检查的是 NET_CAPABILITY_INTERNET and NET_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 successfully validated. For example, for a network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully detected.

因此,您真正需要的是检查活动网络是否具有这两种功能,以确定您是否连接到具有互联网连接的网络。

actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
actNw.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);

我也遇到了同样的问题,当 VPN 已连接且 WiFi 已关闭时,NET_CAPABILITY_VALIDATEDTRANSPORT_VPN 仍然是 return。

而不是 connectivityManager.activeNetwork 使用 connectivityManager.allNetworks

如果 WiFi 开关打开并连接到网络 connectivityManager.allNetworks 将 return 2 个网络,否则它将 return 1 个网络,因为 VPN 是活动的默认网络。