我的问题很简单,Android支持以编程方式检查VPN是否有效(在API 21+上)是指:http://developer.android.com/reference/android/net/ConnectivityManager.html#TYPE_VPN
我以为我知道它应该如何工作但代码(使用roboguice):
@Inject
boolean checkVPN(ConnectivityManager connMgr) {
//don't know why always returns null:
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_VPN);
boolean isVpnConn = networkInfo == null ? false : networkInfo.isConnected();
return isVpnConn;
}
始终返回null。对于WIFI或MOBILE运作良好。
这是一个错误吗?或者我做错了什么?或者我误解了它应该如何运作?
答案 0 :(得分:4)
NetworkCapabilities
适用于API 21+。您必须遍历所有现有网络并检查哪个网络有VPN_TRANSPORT
ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = cm.getAllNetworks();
Log.i(TAG, "Network count: " + networks.length);
for(int i = 0; i < networks.length; i++) {
NetworkCapabilities caps = cm.getNetworkCapabilities(networks[i]);
Log.i(TAG, "Network " + i + ": " + networks[i].toString());
Log.i(TAG, "VPN transport is: " + caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN));
Log.i(TAG, "NOT_VPN capability is: " + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN));
}
答案 1 :(得分:0)
如果要检查当前活动的网络是否正在使用VPN,可以使用:
Network activeNetwork = connectivityManager.getActiveNetwork();
NetworkCapabilities caps = connectivityManager.getNetworkCapabilities(activeNetwork);
boolean vpnInUse = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN);