Android中判断当前网络是否为VPN
java
/**
* 判断当前网络是否为VPN
* @param context
* @return
*/
public static boolean hasVPN(Context context) {
// 查询网络状态,被动监听网络状态变化
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取当前来凝结网络
Network currentNetwork = cm.getActiveNetwork();
// 获取当前网络能力
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(currentNetwork);
// 是否是VPN端口
return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
// 是否为wifi
// return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
// 是否为蜂窝网络
// return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
}
- VPN
java
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
- WIFI
java
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE);
- 蜂窝
java
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
其他读取网络状态可查考- Android网络状态读取。