How to check VPN connection status on Android ICS

前端 未结 4 2091
遥遥无期
遥遥无期 2021-02-05 23:51

I\'m trying to register receiver, that will check VPN status. I have tried this: Get VPN Connection status on Android but looks like it no longer works on ICS. I have checked an

4条回答
  •  逝去的感伤
    2021-02-06 00:56

    NetworkCapabilities worked for me in API 21+. Unfortunately I haven't found a solution for 19-20. You have to loop over all existing networks and check which has 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));
    
    }
    

提交回复
热议问题