VpnService - Android SDK | Android Developers (2024)

java.lang.Object
android.content.Context
android.content.ContextWrapper
android.app.Service
android.net.VpnService

Class Overview

VpnService is a base class for applications to extend and build their own VPN solutions. In general, it creates a virtual network interface, configures addresses and routing rules, and returns a file descriptor to the application. Each read from the descriptor retrieves an outgoing packet which was routed to the interface. Each write to the descriptor injects an incoming packet just like it was received from the interface. The interface is running on Internet Protocol (IP), so packets are always started with IP headers. The application then completes a VPN connection by processing and exchanging packets with the remote server over a tunnel.

Letting applications intercept packets raises huge security concerns. A VPN application can easily break the network. Besides, two of them may conflict with each other. The system takes several actions to address these issues. Here are some key points:

  • User action is required to create a VPN connection.
  • There can be only one VPN connection running at the same time. The existing interface is deactivated when a new one is created.
  • A system-managed notification is shown during the lifetime of a VPN connection.
  • A system-managed dialog gives the information of the current VPN connection. It also provides a button to disconnect.
  • The network is restored automatically when the file descriptor is closed. It also covers the cases when a VPN application is crashed or killed by the system.

There are two primary methods in this class: prepare(Context) and establish(). The former deals with user action and stops the VPN connection created by another application. The latter creates a VPN interface using the parameters supplied to the VpnService.Builder. An application must call prepare(Context) to grant the right to use other methods in this class, and the right can be revoked at any time. Here are the general steps to create a VPN connection:

  1. When the user press the button to connect, call prepare(Context) and launch the returned intent.
  2. When the application becomes prepared, start the service.
  3. Create a tunnel to the remote server and negotiate the network parameters for the VPN connection.
  4. Supply those parameters to a VpnService.Builder and create a VPN interface by calling establish().
  5. Process and exchange packets between the tunnel and the returned file descriptor.
  6. When onRevoke() is invoked, close the file descriptor and shut down the tunnel gracefully.

Services extended this class need to be declared with appropriate permission and intent filter. Their access must be secured by BIND_VPN_SERVICE permission, and their intent filter must match SERVICE_INTERFACE action. Here is an example of declaring a VPN service in AndroidManifest.xml:

 <service android:name=".ExampleVpnService" android:permission="android.permission.BIND_VPN_SERVICE"> <intent-filter> <action android:name="android.net.VpnService"/> </intent-filter> </service>
See Also
  • VpnService.Builder

Summary

Nested Classes
class VpnService.Builder Helper class to create a VPN interface.
Constants
String SERVICE_INTERFACE The action must be matched by the intent filter of this service.
[Expand]

Inherited Constants

From classandroid.app.Service
From classandroid.content.Context
From interfaceandroid.content.ComponentCallbacks2
Public Constructors
VpnService()
Public Methods
IBinder onBind(Intent intent)

Return the communication interface to the service.

void onRevoke()

Invoked when the application is revoked.

static Intent prepare(Context context)

Prepare to establish a VPN connection.

boolean protect(int socket)

Protect a socket from VPN connections.

boolean protect(DatagramSocket socket)

Convenience method to protect a DatagramSocket from VPN connections.

boolean protect(Socket socket)

Convenience method to protect a Socket from VPN connections.

[Expand]

Inherited Methods

From class android.app.Service
From class android.content.ContextWrapper
From class android.content.Context
From class java.lang.Object
From interface android.content.ComponentCallbacks
From interface android.content.ComponentCallbacks2

Constants

public static final String SERVICE_INTERFACE

Added in API level 14

The action must be matched by the intent filter of this service. It also needs to require BIND_VPN_SERVICE permission so that other applications cannot abuse it.

Constant Value: "android.net.VpnService"

Public Constructors

public VpnService ()

Added in API level 14

Public Methods

public IBinder onBind (Intent intent)

Added in API level 14

Return the communication interface to the service. This method returns null on Intents other than SERVICE_INTERFACE action. Applications overriding this method must identify the intent and return the corresponding interface accordingly.

Parameters
intent The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.
Returns
  • Return an IBinder through which clients can call on to the service.
See Also
  • onBind(Intent)

public void onRevoke ()

Added in API level 14

Invoked when the application is revoked. At this moment, the VPN interface is already deactivated by the system. The application should close the file descriptor and shut down gracefully. The default implementation of this method is calling stopSelf().

Calls to this method may not happen on the main thread of the process.

See Also
  • prepare(Context)

public static Intent prepare (Context context)

Added in API level 14

Prepare to establish a VPN connection. This method returns null if the VPN application is already prepared. Otherwise, it returns an Intent to a system activity. The application should launch the activity using startActivityForResult(Intent, int) to get itself prepared. The activity may pop up a dialog to require user action, and the result will come back via its onActivityResult(int, int, Intent). If the result is RESULT_OK, the application becomes prepared and is granted to use other methods in this class.

Only one application can be granted at the same time. The right is revoked when another application is granted. The application losing the right will be notified via its onRevoke(). Unless it becomes prepared again, subsequent calls to other methods in this class will fail.

See Also
  • onRevoke()

public boolean protect (int socket)

Added in API level 14

Protect a socket from VPN connections. The socket will be bound to the current default network interface, so its traffic will not be forwarded through VPN. This method is useful if some connections need to be kept outside of VPN. For example, a VPN tunnel should protect itself if its destination is covered by VPN routes. Otherwise its outgoing packets will be sent back to the VPN interface and cause an infinite loop. This method will fail if the application is not prepared or is revoked.

The socket is NOT closed by this method.

Returns
  • true on success.

public boolean protect (DatagramSocket socket)

Added in API level 14

Convenience method to protect a DatagramSocket from VPN connections.

Returns
  • true on success.
See Also
  • protect(int)

public boolean protect (Socket socket)

Added in API level 14

Convenience method to protect a Socket from VPN connections.

Returns
  • true on success.
See Also
  • protect(int)

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Android 4.2r1 —

About Android| Legal| Support

VpnService - Android SDK | Android Developers (2024)

FAQs

Why does VPN not work on Android? ›

If your VPN isn't connecting on your Android device, there could be various reasons behind it. Things like outdated operating systems, crowded servers, or wrong setups might be culprits. Unreliable VPN providers might also cause your VPN not working on Android.

What is VPN service on Android? ›

VPNs allow devices that aren't physically on a network to securely access the network. Android includes a built-in (PPTP, L2TP/IPSec, and IPSec) VPN client. Devices running Android 4.0 and later also support VPN apps.

What is the VPN service policy? ›

In the VpnService Policy listed: "The VpnService cannot be used to redirect or manipulate user traffic from other apps on a device for monetization purposes (for example, redirecting ads traffic through a country different than that of the user)." What does it mean "traffic from other apps on a device"?

How to restart VPN? ›

Reset the VPN connection: Disconnect from the VPN entirely and reconnect. Sometimes, simply reestablishing the connection can resolve server-related issues. Review security settings: Your firewall or antivirus software might be blocking the connection to the server.

How to get free VPN on Android? ›

ProtonVPN is currently the best free Android VPN.

That's because it has a free version that uses the WireGuard protocol, offers unlimited simultaneous connections, and has a kill switch. Yet, if you're looking for a more advanced VPN solution, NordVPN offers a free 7-day trial.

How do I manually add VPN to my Android? ›

  1. Open your device's Settings app.
  2. Tap Network & internet. VPN. If you can't find it, search for "VPN." If you still can't find it, get help from your device manufacturer.
  3. Tap the VPN you want.
  4. Enter your username and password.
  5. Tap Connect. If you use a VPN app, the app opens.

Do you really need a VPN for Android? ›

Installing a VPN app on your Android is never a bad idea. It will not only make browsing safer, particularly when logged into public Wi-Fi networks, but also allow you to access content restricted to specific regions. And the top VPNs won't bog down your device's memory, either.

Does Android have built-in VPN? ›

VPNs allow devices that aren't physically on a network to securely access the network. Android includes a built-in (PPTP and L2TP/IPSec) VPN client, which is sometimes called legacy VPN.

Do I really need a VPN on Android phone? ›

Smartphones are commonly used to access public Wi-Fi. Even on a password-guarded connection, you are visible to other users on the network. A hacker can get the same coffeeshop password you have, and they can be on the same network as you. Using a VPN will protect yourself with encryption and anonymized data.

How do I know if I'm using a VPN service? ›

You'll know you're connected to a VPN in the following two ways:
  • On the VPN settings page, the VPN connection name will display Connected underneath it.
  • On the taskbar, a blue shield will display when you're connected to a recognized VPN.

Can you trust VPN services? ›

VPN security can protect from IP and encrypt internet history and is increasingly being used to prevent snooping on by government agencies. However, VPNs won't be able to keep you safe in all scenarios.

Should I allow VPN access? ›

VPNs ensure data protection from hackers and secure browsing. In result, this prevents advertisers or ISPs from accessing your browsing data. At the same time, there may be times when you need to turn your VPN off. That is when you need to access local sites or devices, such as streaming platforms or a printer.

How do I clear VPN on my phone? ›

How to delete a VPN
  1. Go to “Settings” and click on “Apps.”
  2. Select “Apps & features” in the left menu.
  3. Select your VPN app and click on it.
  4. Click “Uninstall” and confirm by clicking a pop-up.
Mar 28, 2023

How do I reset my VPN on Android? ›

Try resetting your network settings:
  1. Open the Settings app on your Android.
  2. Scroll to and tap either "General management" or "System," depending on what device you have.
  3. Tap either "Reset" or "Reset options."
  4. Tap on "Reset network settings."
  5. You'll have to confirm that you want to reset your network settings. Do so.

Why is VPN not working on my phone? ›

VPN not working on Android

Your VPN app might be interfering with other apps or settings on your device. You can fix an unstable VPN connection on Android by changing your VPN protocol, turning off battery-saving mode, switching to another server, or simply restarting your device.

Why is my phone blocking VPN? ›

VPNs typically get blocked due to government censorship, copyright concerns, streaming location restrictions, or school and workplace restrictions.

How do I enable VPN on Android? ›

Changing Android VPN Settings

Setting up a VPN is truly as easy as installing it, signing in, and connecting. However, once you're in, you might want to play around with the settings. You can find the following settings on the Android's main settings page, then Network & Internet, Advanced, VPN, and Settings.

Why can't I use a VPN on my phone? ›

If your VPN is not connecting, you can try a few ways to fix the issue:
  1. Check your internet connection. ...
  2. Check your credentials. ...
  3. Check your VPN server status. ...
  4. Check your VPN protocol and ports. ...
  5. Look for VPN software issues. ...
  6. Check the firewall blocking. ...
  7. Restart your VPN app. ...
  8. Reinstall the latest version of your VPN app.

Why does my VPN not want to work? ›

The VPN server might be experiencing downtime or technical issues. You may not have entered your login credentials correctly or may be using an expired password, preventing your VPN from connecting. You may have fallen foul of location-based restrictions. In some countries, VPNs are illegal.

Top Articles
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 6219

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.