vpn检测

2021-05-07  本文已影响0人  CentForever

检测手机是否打开vpn

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build

fun Context.isUsingVpn(): Boolean? {
    var vpnInUse = false
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val activeNetwork = connectivityManager?.activeNetwork
        val caps = connectivityManager?.getNetworkCapabilities(activeNetwork)
        return caps?.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
    }
    val networks = connectivityManager?.allNetworks
    networks?.let {
        for (i in networks.indices) {
            val caps = connectivityManager.getNetworkCapabilities(networks[i])
            if (caps?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) {
                vpnInUse = true
                break
            }
        }
    }
    return vpnInUse
}
上一篇下一篇

猜你喜欢

热点阅读