[英]Android VpnService - How to check VpnService if it was started?
I have two applications that uses VpnService class. 我有两个使用VpnService类的应用程序。 But there can be only one VPN connection running at the same time.
但是,同时只能运行一个VPN连接。 The existing interface is deactivated when a new one is created and I want the new application not to start vpnservice to avoid old one getting deactivated and its VPN connection.
创建新接口时,现有接口将被停用,并且我希望新应用程序不启动vpnservice以避免旧应用程序停用及其VPN连接。 So I want to check if another vpnservice was started before invoke startService().
所以我想在调用startService()之前检查是否启动了另一个vpnservice。
Is there any api to do this ? 这有什么api吗?
As far as I know you can not check directly.The below is the approach that I use in my application for checking VPN connection. 据我所知你不能直接检查。以下是我在我的应用程序中用于检查VPN连接的方法。
1)Make a HTTPGet call for http://jsonip.com 1)为http://jsonip.com进行HTTPGet调用
public static String GetDeviceIp(){
HttpGet req = new HttpGet("http://jsonip.com");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(req);
if (response.getStatusLine().getStatusCode() == 200){
ipaddress=parseJson(response.getEntity().getContent());
}else
{ ipaddress ="EMPTY" }
return ipaddress
}
2)Parse the json response and extract the Ip address from response 2)解析json响应并从响应中提取IP地址
public static String parseJson(InputStream in)
{
String iP;
try{
String result;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
iP=jsonObject.getString("ip");
}catch (Exception e){
iP="EMPTY";
}
return iP;
}
3)Compare if VPN server Ip and extracted Ip are equal if so then the VPN is on else VPN is off 3)比较VPN服务器Ip和提取的Ip是否相等,如果是,则VPN开启,否则VPN关闭
public static boolean IsVPNON(){
return GetDeviceIp().equals("VPN-IP address");}
While above approach works, it is more or less a hack and requires sending an HTTP request. 虽然上述方法有效,但它或多或少都是黑客攻击,需要发送HTTP请求。
Since this seems like a one-off check you want to run before starting another VPN, you can check whether VPN network is part of all available networks. 由于这似乎是在启动另一个VPN之前要运行的一次性检查,因此您可以检查VPN网络是否是所有可用网络的一部分。
private boolean isAnyVpnConnected(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
Network[] networks = connectivityManager.getAllNetworks();
if (networks == null) {
return false;
}
for (Network network : networks) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)) {
return true;
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.