检查Android中的VPN连接是否处于活动状态?

我在我的无根Android 4.4设备上有第三方VPN应用程序,并且希望编写后台服务来监视VPN连接,并在VPN连接断开时提醒用户。

有没有办法做到这一点? 我找不到使用VPNService API的任何方法。

感谢:D

这对我很有用:testing从API 16到23:

List<String> networkList = new ArrayList<>(); try { for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) { if (networkInterface.isUp()) networkList.add(networkInterface.getName()); } } catch (Exception ex) { Timber.d("isVpnUsing Network List didn't received"); } return networkList.contains("tun0"); 

PS也可以是另一个名为“ppp0”的networkInterface,但是在我testing不同的VPN应用程序时,它总是“tun0”

使用NetworkCapabilities为我工作。 您必须遍历所有现有的networking,并检查哪些具有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)); } 

写一个小的应用程序,打一个内部网页或ping一个内部网站…

 HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(internal_url); HttpResponse response = client.execute(request); String html = ""; InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { str.append(line); } in.close(); html = str.toString(); 

要么

 String str = ""; try { Process process = Runtime.getRuntime().exec( "/system/bin/ping -c 8 " + internal_url); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); int i; char[] buffer = new char[4096]; StringBuffer output = new StringBuffer(); while ((i = reader.read(buffer)) > 0) output.append(buffer, 0, i); reader.close(); str = output.toString(); } catch (IOException e) { e.printStackTrace(); } return str; 

如何检查networking信息? 如果有一种types的VPN,我会假设有一个VPN连接。

需要ACCESS_NETWORK_STATE权限。

  List<NetworkInfo> connectedNetworks = new ArrayList<>(); if (Build.VERSION.SDK_INT >= 21) { Network[] networks = m_ConnectivityManager.getAllNetworks(); for (Network n : networks) { NetworkInfo ni = m_ConnectivityManager.getNetworkInfo(n); if (ni.isConnectedOrConnecting()) { connectedNetworks.add(ni); } } } else { NetworkInfo[] nis = m_ConnectivityManager.getAllNetworkInfo(); for (NetworkInfo ni : nis) { if (ni.isConnectedOrConnecting()) { connectedNetworks.add(ni); } } } boolean bHasVPN = false; if (Build.VERSION.SDK_INT >= 21) { for (NetworkInfo ni : connectedNetworks) { bHasVPN |= (ni.getType() == ConnectivityManager.TYPE_VPN); } }