Jump to content
Sign in to follow this  
Aamgian

How check VPN Active on Android?

Recommended Posts

Hello,

 

How do I know if there is a VPN connection on the device that is active, because my application will ignore if using VPN?

I use this code but it doesn't seem to work.

function TPlatformConnectivity.IsVPNConnection: Boolean;
var
  LManager: JConnectivityManager;
  LAllNetworks: TJavaObjectArray<JNetwork>;
  LCapabilities: JNetworkCapabilities;
  I: Integer;
begin
  Result := False;
  LManager := ConnectivityManager;
  LAllNetworks := LManager.getAllNetworks;
  for I := 0 to LAllNetworks.Length - 1 do
  begin
    LCapabilities := LManager.getNetworkCapabilities(LAllNetworks[I]);
    if (LCapabilities <> nil) and LCapabilities.hasCapability(TJNetworkCapabilities.JavaClass.TRANSPORT_VPN) then
    //if (LCapabilities <> nil) and LCapabilities.hasCapability(TJNetworkCapabilities.JavaClass.TRANSPORT_VPN) then
    begin
      Result := True;
      Break;
    end;
  end;
end;

 

Thanks You

 

Share this post


Link to post

That code just checks if the network being examined has VPN capability, not if it is actually available, nor if it is connected. Note that a device can have an active VPN connection as well as other active connections. For guidance, you may wish to look at the Java examples here:

 

https://www.codota.com/code/java/methods/android.net.NetworkCapabilities/hasTransport

 

and here:

 

https://www.codota.com/code/java/methods/android.net.NetworkCapabilities/hasTransport

(specifically example 19)

Share this post


Link to post

Thanks Dave, at least the VPN connection on the device can be known

 

this code work i tested with android 9 and 10.

function TPlatformConnectivity.IsVPNConnection: Boolean;
var
  LManager: JConnectivityManager;
  LAllNetworks: TJavaObjectArray<JNetwork>;
  LCapabilities: JNetworkCapabilities;
  I: Integer;
begin
  Result := False;
  LManager := ConnectivityManager;
  LAllNetworks := LManager.getAllNetworks;
  for I := 0 to LAllNetworks.Length - 1 do
  begin
    LCapabilities := LManager.getNetworkCapabilities(LAllNetworks[I]);
    if (LCapabilities <> nil) and LCapabilities.hasTransport(TJNetworkCapabilities.JavaClass.TRANSPORT_VPN) then
    begin
      Result := True;
      Break;
    end;
  end;
end;

 

Edited by Aamgian
  • Like 2

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×