Android中判断当前网络是否为VPN
/*** 判断当前网络是否为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
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
- WIFI
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE);
- 蜂窝
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
其他读取网络状态可查考- Android网络状态读取。