我有两个使用 VpnService 类的应用程序。但同时只能有一个 VPN 连接运行。创建新接口时,现有接口将被停用,我希望新应用程序不要启动 vpnservice 以避免旧接口及其 VPN 连接被停用。所以我想在调用 startService() 之前检查是否启动了另一个 vpnservice。
有没有 api 可以做到这一点?
据我所知,你不能直接检查。以下是我在我的应用程序中用于检查 VPN 连接的方法。
1) 进行 HTTPGet 调用http://jsonip.com http://jsonip.com
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)解析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)比较VPN服务器IP和提取的Ip是否相等,如果相等则VPN打开,否则VPN关闭
public static boolean IsVPNON(){
return GetDeviceIp().equals("VPN-IP address");}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)