# How to Build an Android VPN App with VpnService: 8 Steps

> How to build an Android VPN app with VpnService: manifest, consent, Builder, packets, protect(), foreground service, revocation and a test table for each step.

Source: https://digitaldtech.com/blog/how-to-build-an-android-vpn-app-with-vpnservice/
Published: 2026-11-26 | Updated: 2026-11-26
Author: ST Muntaha
Publisher: DigitalD.tech (https://digitaldtech.com/)


Google's VPN guide lists the calls in a connect sequence. A working client also has to survive revoked consent, a killed service and a network switch. This is how to build an Android VPN app on `VpnService` in eight steps: declare the service, get consent with `VpnService.prepare()`, protect the tunnel socket, configure and `establish()` the interface, move packets over its file descriptor, run as a foreground service, handle revocation, and survive network changes.

At the end you have a client skeleton that connects to a test server. You do not have a tunnel protocol, a server, authentication or billing, because `VpnService` supplies none of them.

## What You Need Before You Build an Android VPN App

`VpnService` creates a virtual network interface and returns a file descriptor. Each read gives your app an outgoing IP packet. Each write injects an incoming one. Everything between those two calls is yours: protocol, encryption, server and accounts. Our guide to the [six components of a VPN app](https://digitaldtech.com/blog/vpn-app-architecture-six-components/) shows where this client sits in the whole product.

- **A throwaway tunnel server** you control. Every VpnService example here is a sketch drawn from the [VpnService source](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/android/net/VpnService.java) and Google's ToyVpn sample, so try it on a test server and a test device first.
- **Two test devices:** one on Android 14 or higher, one on your lowest supported version. Always on VPN starts at Android 7.0 (API 24), and foreground promotion matters from Android 8.0 (API 26), per Google's [VPN guide](https://developer.android.com/develop/connectivity/vpn).

## Step 1: Declare the Service in the Manifest

A VPN service must be secured with the `BIND_VPN_SERVICE` permission, and its intent filter must match the `android.net.VpnService` action. The guide says the permission exists so only the system can bind to your service. Add the foreground service permission and a type attribute now. Step 6 explains the type.

```xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- plus the permission that matches your service type (Step 6) -->

<service android:name=".ExampleVpnService"
    android:permission="android.permission.BIND_VPN_SERVICE"
    android:exported="false"
    android:foregroundServiceType="TYPE_FROM_STEP_6">
    <intent-filter>
        <action android:name="android.net.VpnService"/>
    </intent-filter>
</service>
```

Apps that target Android 12 or higher must set `android:exported` on a service with an intent filter, or the build or install fails, per the [Android 12 behavior changes](https://developer.android.com/about/versions/12/behavior-changes-12). That page says `false` in most cases, so the sketch uses it; the Javadoc and ToyVpn examples omit it. No Android page addresses this value for a `VpnService`, so test it on a device, including an always on start after a reboot.

It worked when `establish()` later returns a descriptor. If the declaration is wrong, `establish()` throws a `SecurityException`, which its Javadoc ties to a service that is not properly declared.

## Step 2: Ask for Consent with VpnService.prepare()

Call `prepare()` from an activity every time the user taps connect. It returns `null` if the app is already prepared. Otherwise it returns an intent for a system consent screen. Do not cache the answer. Only one app holds the VPN right at a time, another VPN app can take it, and the user can switch the VPN off at any moment.

```java
Intent intent = VpnService.prepare(this);
if (intent != null) {
    startActivityForResult(intent, 0);
} else {
    onActivityResult(0, RESULT_OK, null);
}

@Override
protected void onActivityResult(int request, int result, Intent data) {
    if (result == RESULT_OK) {
        startService(new Intent(this, ExampleVpnService.class));
    }
}
```

It worked when the first run shows the system dialog and a later run skips it. It fails when code calls `establish()` without being prepared: that returns `null`, so treat `null` as "stop and ask again".

## Step 3: Protect the Tunnel Socket, Then Connect It

Your tunnel reaches your server over an ordinary socket. If your routes cover the server's address, that socket's packets enter the VPN interface and loop. `protect()` sends a socket's traffic straight to the underlying network. It returns `true` on success, does not close the socket, and fails if the app is not prepared or has been revoked. Google's guide calls it before connecting the socket.

```java
DatagramChannel tunnel = DatagramChannel.open();
if (!protect(tunnel.socket())) {
    throw new IllegalStateException("Cannot protect the tunnel");
}
tunnel.connect(serverAddress);
```

Two notes. ToyVpn resolves the server name before the interface exists, with a comment saying to fetch anything that needs the network first, so do the same. And `protect()` has an overload that takes a raw file descriptor, so in our reading a native core can hand you each socket it opens through a callback into your service.

It worked when `protect()` returns `true` and the handshake completes. The failure is a tunnel that never connects, or spins, because one socket was never protected.

## Step 4: Configure and Establish the Interface

Your server's handshake supplies the values, as it does in ToyVpn. Feed them to `VpnService.Builder`:

```java
VpnService.Builder builder = new Builder();
builder.setSession("Example VPN")
       .setMtu(1400)
       .addAddress("10.0.0.2", 32)
       .addRoute("0.0.0.0", 0)
       .addDnsServer(dnsFromServer);
ParcelFileDescriptor tun = builder.establish();
if (tun == null) { /* not prepared or revoked: stop */ }
```

`addAddress()` needs at least one address. `addRoute()` with `0.0.0.0/0` or `::/0` sends all traffic of that family into the tunnel. `setSession()` names the connection in system dialogs and notifications. For per app rules, use `addAllowedApplication()` or `addDisallowedApplication()`, never both.

Know three defaults from the Javadoc. With no `addDnsServer()` call, the default network's DNS servers are used. With no address, route or DNS server of a family, that family's outgoing traffic is blocked, and `allowFamily()` can let it fall through to the underlying network instead. With no `setMtu()`, the system default applies. Our [leak test plan](https://digitaldtech.com/blog/vpn-dns-ipv6-leak-test-plan/) turns these into checks.

It worked when `establish()` returns a descriptor and the system shows its own VPN notification. It throws `IllegalArgumentException` or `IllegalStateException` when the system rejects or cannot apply a parameter.

## Step 5: Move Packets Between the Descriptor and the Tunnel

Packets always start with IP headers. Reads return outgoing packets, writes inject incoming ones.

```java
tunnel.configureBlocking(false);           // one thread reads both sides, as in ToyVpn
FileInputStream in = new FileInputStream(tun.getFileDescriptor());
FileOutputStream out = new FileOutputStream(tun.getFileDescriptor());
ByteBuffer packet = ByteBuffer.allocate(Short.MAX_VALUE);

int length = in.read(packet.array());      // device to server
if (length > 0) {
    packet.limit(length);
    tunnel.write(packet);                  // encrypt and frame here
    packet.clear();
}
length = tunnel.read(packet);              // server to device
if (length > 0) {
    out.write(packet.array(), 0, length);  // decrypt first
    packet.clear();
}
```

The descriptor is non blocking by default and `setBlocking()` changes that. ToyVpn also makes its tunnel channel non blocking, then polls and sleeps 100 milliseconds when idle, and its own comment calls a blocking read on another thread cleaner. Its buffer is `Short.MAX_VALUE` because the MTU is a signed short.

Google's guide says your app must use strong encryption to and from the gateway. ToyVpn's handshake sends its secret in plaintext and says so. Close the descriptor when the connection ends: the Javadoc says the system then restores the network, including after a crash or kill.

It worked when a browser on the device loads a page through your server. Our reading: a buffer smaller than your MTU truncates packets. The other failure is shipping the unencrypted sketch.

## Step 6: Run It as a Foreground Service

The system starts a VPN service in the background with `startService()`. From Android 8.0 it allowlists the app briefly, and the app must promote itself to the foreground or the system shuts it down. ToyVpn calls `startForeground()` first thing, and its comment says a background VPN service can be killed before it receives `onRevoke()`. The guide asks for a non dismissible notification while the service is active, but on Android 14 or higher users can dismiss ongoing notifications, per the [Android 14 behavior changes](https://developer.android.com/about/versions/14/behavior-changes-all). On Android 13 or higher the notification appears in the drawer only if the user grants `POST_NOTIFICATIONS`; the foreground service starts without it, per the [notification permission guide](https://developer.android.com/develop/ui/views/notifications/notification-permission).

```java
startForeground(1, notification); // two argument form: types come from the manifest
```

Apps that target Android 14 or higher must declare a foreground service type, per the [types page](https://developer.android.com/develop/background-work/services/fgs/service-types). As of 31 October 2026 Google's pages point two ways:

| Type | What supports it | What is missing or risky |
|---|---|---|
| `systemExempted` | The types page lists VPN apps configured in system VPN settings. The [`ServiceInfo` source](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/android/content/pm/ServiceInfo.java) lists "Active VPN apps", and the [`ForegroundServiceTypePolicy` source](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/android/app/ForegroundServiceTypePolicy.java) accepts the `OP_ACTIVATE_VPN` app op as one way to qualify. Needs `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`. | The VPN guide names no type. No documentation page we read says a `VpnService` maps to it. [Play's declaration help](https://support.google.com/googleplay/android-developer/answer/13392821) does not mention it. Declaring it without qualifying throws `ForegroundServiceTypeNotAllowedException`. |
| `specialUse` | The [ToyVpn manifest](https://android.googlesource.com/platform/development/+/refs/heads/main/samples/ToyVpn/AndroidManifest.xml) uses it with the `PROPERTY_SPECIAL_USE_FGS_SUBTYPE` property set to `vpn`. Needs `FOREGROUND_SERVICE_SPECIAL_USE`. | The types page lists VPN apps under the other type and says these values are reviewed at Play Console submission. Play's declaration help says it may be declared in limited scenarios. |

We found no page that says which one Play expects for a `VpnService`. Test both on a real Android 14 or higher device, from the app and from a system started always on VPN, and keep your manifest consistent with what the App content form asks. Our [target API guide](https://digitaldtech.com/blog/google-play-target-api-vpn-apps-2026/) covers the Android 14 to 17 changes around it.

It worked when the service starts and keeps running with the screen off. Per Google's pages, an app that targets Android 14 or higher gets `MissingForegroundServiceTypeException` for no declared type, `ForegroundServiceTypeNotAllowedException` for an unqualified type, or `SecurityException` for a missing permission. Confirm each on your device.

## Step 7: Handle Revocation, Always On and Lockdown

When another VPN app takes over, the system calls `onRevoke()`. The interface is already deactivated, another interface is already routing traffic, and the call may not come on the main thread. Close the descriptor and the tunnel socket, stop the loop, and update your UI. The default implementation calls `stopSelf()`.

Always on VPN lets the system start your service at boot and keep it running, so it can start with no UI. Save the connection settings between starts. The guide shows how to tag your own start intents to spot a system start, and `VpnService` also has `isAlwaysOn()` and `isLockdownEnabled()`, which were added in API level 29 (Android 10). If your app cannot support always on VPN yet, set the `android.net.VpnService.SUPPORTS_ALWAYS_ON` meta data to false to opt out (Android 8.1 or higher). With "Block connections without VPN" on, apps outside your allowed or disallowed lists lose their connection. Our [kill switch guide](https://digitaldtech.com/blog/vpn-kill-switch-how-it-works/) covers both settings.

It worked when starting a second VPN app triggers `onRevoke()` and your UI shows disconnected. It fails when the service keeps running a loop on a closed descriptor.

## Step 8: Handle Network Changes and Reconnect

Google's VPN guide gives no procedure for this. Android's [network state guide](https://developer.android.com/develop/connectivity/network-ops/reading-network-state) describes `registerDefaultNetworkCallback()` and a `NetworkCallback` whose `onAvailable()` and `onLost()` report changes of the default network. It also says connections left on the previous default network are forcefully terminated later. Our reading, for a connected socket like the one in Step 3: after a switch the old tunnel socket is stale, so create a new socket, `protect()` it and reconnect. Other socket designs may need less, so test yours. Whether the interface stays up meanwhile is a design choice.

If you bind protected sockets to a `Network`, call `setUnderlyingNetworks()` each time your set changes. A `null` value means the system default. ToyVpn retries in a loop, and its comment says the better way is to work with `ConnectivityManager`.

It worked when a transfer resumes after Wi Fi switches to cellular and your server sees the new source address. It fails when the new socket is not protected.

## How Do You Test an Android VPN App?

These are our suggested tests, not documented platform behavior. Capture at a gateway you control for the network checks.

| Step | What it prevents | How to test |
|---|---|---|
| 1 Manifest | `SecurityException`, other apps binding | Release build, connect, confirm a descriptor |
| 2 Consent | `null` descriptor, lost VPN slot | Fresh install, then start another VPN app and reconnect |
| 3 Protect | Tunnel packets looping | Connect with a `0.0.0.0/0` route and watch CPU and the server log |
| 4 Builder | DNS and IPv6 leaks | Capture DNS and IPv6, per the leak plan |
| 5 Packets | Dropped or truncated packets | Large downloads, ping at full MTU, compare checksums |
| 6 Foreground | Shutdown, type exceptions | Connect, screen off, reboot with always on, on Android 14 or higher |
| 7 Revocation | Zombie service, false "connected" UI | Start another VPN app, toggle "Block connections without VPN" |
| 8 Network change | Dead tunnel after a switch | Wi Fi to cellular mid transfer, airplane mode, check the egress IP |

## FAQ

### Does VpnService encrypt my traffic?

No. `VpnService` gives you an interface and a file descriptor, and encryption is your tunnel's job. Google's guide says the app must use strong encryption between the device and the gateway.

### Can I use ToyVpn as the base of a production app?

No. Its server comments say not to use it in production, and its handshake sends the shared secret in plaintext. Use it to learn the call order, then replace the tunnel with a real protocol.

### Which foreground service type should a VPN app declare?

Google's pages do not say. As of 31 October 2026 the types page lists VPN apps under `systemExempted`, while Google's ToyVpn manifest uses `specialUse` with the subtype `vpn`. Test both on Android 14 or higher.

### Can two VPN apps run at the same time on Android?

Not within one user or work profile. A new service stops the existing one, and that app receives `onRevoke()`. Each user or work profile can run its own VPN app.

### Will Google Play accept my VPN app?

Not unless VPN is the app's core functionality, with the exceptions the [policy](https://support.google.com/googleplay/android-developer/answer/12564964) lists. It also requires the VpnService declaration form, encryption to the tunnel endpoint, and an in app disclosure with consent for personal or sensitive data. This is not legal advice, so read the policy yourself.

## The Short Version

To build an Android VPN app, get the order right: declare, consent, protect, establish, pump packets, stay in the foreground, and rebuild on every network change. The tunnel protocol, server and accounts are still ahead of you.

Briefing a developer on an Android client, or unsure how much sits around `VpnService`? DigitalD.tech's [custom VPN app development](https://digitaldtech.com/services/custom-vpn-app-development/) covers native Android (VpnService) and iOS clients plus the panel, billing and servers behind them. Tell us your plan and we'll tell you what we'd do in your position.

*Last checked against Android's VPN guide, foreground service types page, network state guide and Android 12 behavior changes, the VpnService, ServiceInfo and ForegroundServiceTypePolicy source on Android's main branch, the ToyVpn sample, and Google Play Console Help on 31 October 2026.*

