# API Reference

## UnifiedSdk

The main entry point for the VPN SDK. Provides access to all SDK functionality including VPN connection management, authentication, and configuration.

### Initialization

See [Initialization](/paas/sdk/vpn-sdk-for-android/usage/initialization.md).

### Methods

#### `init(Context context, ClientInfo clientInfo, UnifiedSdkConfig config)`

Initializes the SDK with the provided configuration.

**Parameters:**

* `context` - Android application context
* `clientInfo` - Client configuration with carrier ID and server URLs
* `config` - SDK configuration options

#### `getInstance()`

Returns the singleton instance of UnifiedSdk.

**Returns:** `UnifiedSdk` instance

#### `setLogging(Boolean enabled)`

Enables or disables SDK logging.

**Parameters:**

* `enabled` - true to enable logging, false to disable

## Vpn

Interface for managing VPN connections.

### Methods

#### `start(SessionConfig sessionConfig, CompletableCallback callback)`

Starts a VPN connection with the specified configuration.

**Parameters:**

* `sessionConfig` - VPN session configuration
* `callback` - Completion callback

**Example:**

```java
SessionConfig config = new SessionConfig.Builder()
    .withLocation("us")
    .withReason(TrackingConstants.GprReasons.M_UI)
    .build();

sdk.getVpn().start(config, new CompletableCallback() {
    @Override
    public void complete() {
        // VPN started successfully
    }

    @Override
    public void error(VpnException e) {
        // Handle error
    }
});
```

#### `stop(String reason, CompletableCallback callback)`

Stops the active VPN connection.

**Parameters:**

* `reason` - Reason for stopping (for analytics)
* `callback` - Completion callback

#### `restart(SessionConfig sessionConfig, CompletableCallback callback)`

Restarts the VPN connection with new configuration.

**Parameters:**

* `sessionConfig` - New session configuration
* `callback` - Completion callback

#### `updateConfig(SessionConfig sessionConfig, CompletableCallback callback)`

Updates the configuration of an active VPN session without disconnecting.

**Parameters:**

* `sessionConfig` - Updated session configuration
* `callback` - Completion callback

#### `getStartTimestamp(Callback<Long> callback)`

Gets the timestamp when the current VPN session started.

**Parameters:**

* `callback` - Callback with timestamp in milliseconds

## Backend

Interface for authentication and user management.

See [Backend interface](/paas/sdk/vpn-sdk-for-android/usage/backend-interface.md).

### Methods

#### `login(AuthMethod auth, Callback<User> callback)`

Authenticates a user with the backend.

**Parameters:**

* `auth` - Authentication method (e.g., `AuthMethod.pango(token)`, `AuthMethod.firebase(token)`)
* `callback` - Callback with User object on success

**Example:**

```java
sdk.getBackend().login(AuthMethod.pango("YOUR_PANGO_ACCESS_TOKEN"), new Callback<User>() {
    @Override
    public void success(User user) {
        // Login successful
    }

    @Override
    public void failure(VpnException e) {
        // Handle login failure
    }
});
```

#### `logout(CompletableCallback callback)`

Logs out the current user.

**Parameters:**

* `callback` - Completion callback

#### `currentUser(Callback<User> callback)`

Gets the currently authenticated user.

**Parameters:**

* `callback` - Callback with current User or null

#### `isLoggedIn(Callback<Boolean> callback)`

Checks if a user is currently logged in.

**Parameters:**

* `callback` - Callback with login status

#### `locations(ConnectionType connectionType, Callback<AvailableLocations> callback)`

Gets available VPN server locations.

**Parameters:**

* `connectionType` - Type of connection (e.g., `ConnectionType.HYDRA_TCP`)
* `callback` - Callback with available locations

#### `remainingTraffic(Callback<RemainingTraffic> callback)`

Gets remaining traffic allowance for the current user.

**Parameters:**

* `callback` - Callback with remaining traffic information

#### `getAccessToken(Callback<String> callback)`

Gets the current access token.

**Parameters:**

* `callback` - Callback with access token

#### `purchase(String rawJson, CompletableCallback callback)`

Processes a purchase transaction.

**Parameters:**

* `rawJson` - Purchase data in JSON format
* `callback` - Completion callback

## Data Models

### ClientInfo

Configuration for SDK initialization.

See [Backend URL Configuration](/paas/sdk/vpn-sdk-for-android/setup/backend-url-configuration.md).

#### Builder Methods

```java
ClientInfo clientInfo = new ClientInfo.Builder()
    .carrierId("your_carrier_id")
    .addUrl("https://api.example.com")
    .build();
```

| Method              | Description                     |
| ------------------- | ------------------------------- |
| `carrierId(String)` | Sets the carrier identifier     |
| `addUrl(String)`    | Adds a backend server URL       |
| `build()`           | Creates the ClientInfo instance |

### SessionConfig

Configuration for VPN sessions.

See [VPN Interface](/paas/sdk/vpn-sdk-for-android/usage/vpn-interface.md).

#### Builder Methods

```java
SessionConfig config = new SessionConfig.Builder()
    .withLocation("us")
    .withReason(TrackingConstants.GprReasons.M_UI)
    .withTransport(TransportMode.HYDRA_TCP)
    .withPolicy(SessionConfig.Policy.OPTIMAL_LOCATION)
    .withPrivateGroup("group_id")
    .withFireshieldConfig(fireshieldConfig)
    .build();
```

| Method                                   | Description                          |
| ---------------------------------------- | ------------------------------------ |
| `withLocation(String)`                   | Sets the VPN server location         |
| `withReason(String)`                     | Sets connection reason for analytics |
| `withTransport(TransportMode)`           | Sets VPN transport protocol          |
| `withPolicy(Policy)`                     | Sets connection policy               |
| `withPrivateGroup(String)`               | Sets private server group            |
| `withFireshieldConfig(FireshieldConfig)` | Sets content filtering configuration |
| `withDnsRules(List<DnsRule>)`            | Sets custom DNS rules                |
| `withBypassDomains(List<String>)`        | Sets domains to bypass VPN           |
| `build()`                                | Creates the SessionConfig instance   |

#### Policy Enum

| Value               | Description                          |
| ------------------- | ------------------------------------ |
| `OPTIMAL_LOCATION`  | Automatically select best location   |
| `PRIORITY_LOCATION` | Use specified location with fallback |
| `STRICT_LOCATION`   | Use only specified location          |

#### AppPolicy

Controls which installed apps route their traffic through the VPN tunnel.

```java
AppPolicy policy = AppPolicy.newBuilder()
    .policy(AppPolicy.POLICY_FOR_LIST)
    .appList(Arrays.asList("com.example.app1", "com.example.app2"))
    .build();
```

| Constant             | Value | Description                                              |
| -------------------- | ----- | -------------------------------------------------------- |
| `POLICY_ALL`         | `0`   | Route all installed apps through the VPN (default)       |
| `POLICY_FOR_LIST`    | `1`   | Route only apps in `appList` through the VPN             |
| `POLICY_EXCEPT_LIST` | `2`   | Route all apps through the VPN except those in `appList` |

| Method                          | Description                                              |
| ------------------------------- | -------------------------------------------------------- |
| `AppPolicy.newBuilder()`        | Returns a new `Builder` instance                         |
| `AppPolicy.forAll()`            | Returns an `AppPolicy` configured with `POLICY_ALL`      |
| `Builder.policy(int)`           | Sets the policy mode (one of the constants above)        |
| `Builder.appList(List<String>)` | Sets the list of app package names the policy applies to |
| `Builder.build()`               | Creates the `AppPolicy` instance                         |

### VpnState

Enum representing VPN connection states.

| State                    | Description                     |
| ------------------------ | ------------------------------- |
| `IDLE`                   | VPN is not connected            |
| `CONNECTING_CREDENTIALS` | Fetching connection credentials |
| `CONNECTING_PERMISSIONS` | Requesting VPN permissions      |
| `CONNECTING_VPN`         | Establishing VPN connection     |
| `CONNECTED`              | VPN is connected                |
| `PAUSED`                 | VPN is paused                   |
| `DISCONNECTING`          | VPN is disconnecting            |
| `ERROR`                  | VPN encountered an error        |
| `UNKNOWN`                | Unknown state                   |

### SessionInfo

Information about the current VPN session.

| Property           | Type               | Description                    |
| ------------------ | ------------------ | ------------------------------ |
| `vpnState`         | `VpnState`         | Current connection state       |
| `sessionConfig`    | `SessionConfig`    | Active session configuration   |
| `credentials`      | `VpnCredentials`   | Connection credentials         |
| `transport`        | `TransportInfo`    | Transport protocol information |
| `connectionStatus` | `ConnectionStatus` | Detailed connection status     |

### TrafficStats

Network traffic statistics.

| Property  | Type   | Description       |
| --------- | ------ | ----------------- |
| `bytesTx` | `long` | Bytes transmitted |
| `bytesRx` | `long` | Bytes received    |

### User

User account information.

| Property      | Type         | Description              |
| ------------- | ------------ | ------------------------ |
| `id`          | `String`     | User identifier          |
| `accessToken` | `String`     | Authentication token     |
| `subscriber`  | `Subscriber` | Subscription information |

### AvailableLocations

Container for available VPN locations.

| Method           | Description                       |
| ---------------- | --------------------------------- |
| `getLocations()` | Returns list of Location objects  |
| `getOptimal()`   | Returns optimal location for user |

### Location

VPN server location.

| Property  | Type     | Description                       |
| --------- | -------- | --------------------------------- |
| `country` | `String` | Country code (ISO 3166-1 alpha-2) |
| `city`    | `String` | City name                         |
| `hub`     | `String` | Server hub identifier             |

## Callbacks and Listeners

### CompletableCallback

Callback for operations without return values.

```java
public interface CompletableCallback {
    void complete();
    void error(VpnException e);
}
```

### Callback

Generic callback for operations with return values.

```java
public interface Callback<T> {
    void success(T data);
    void failure(VpnException e);
}
```

### VpnStateListener

Listener for VPN state changes.

```java
public interface VpnStateListener {
    void vpnStateChanged(VpnState state);
    void vpnError(VpnException e);
}
```

**Registration:**

```java
sdk.getVpn().addVpnStateListener(new VpnStateListener() {
    @Override
    public void vpnStateChanged(VpnState state) {
        // Handle state change
    }

    @Override
    public void vpnError(VpnException e) {
        // Handle error
    }
});
```

### TrafficListener

Listener for traffic statistics updates.

See [Listening for VPN Status and Traffic Updates](/paas/sdk/vpn-sdk-for-android/usage/vpn-interface.md#listening-for-vpn-status-and-traffic-updates).

```java
public interface TrafficListener {
    void onTrafficUpdate(TrafficStats stats);
}
```

## Authentication Methods

See [Authentication](/paas/sdk/unified-vpn-sdk/features/authentication.md).

### AuthMethod

Factory class for creating authentication methods.

#### Static Methods

| Method                                | Description                        | Example                                  |
| ------------------------------------- | ---------------------------------- | ---------------------------------------- |
| `pango(String token)`                 | Pango authentication (Recommended) | `AuthMethod.pango(pangoToken)`           |
| `firebase(String token)`              | Firebase authentication            | `AuthMethod.firebase(firebaseToken)`     |
| `custom(String method, String token)` | Custom authentication              | `AuthMethod.custom("oauth", oauthToken)` |
| `github(String token)`                | GitHub authentication              | `AuthMethod.github(githubToken)`         |

## Exceptions

### VpnException

Base exception class for SDK errors.

| Property  | Type        | Description      |
| --------- | ----------- | ---------------- |
| `message` | `String`    | Error message    |
| `code`    | `int`       | Error code       |
| `cause`   | `Throwable` | Underlying cause |

#### Common Error Codes

| Code                    | Description                  |
| ----------------------- | ---------------------------- |
| `TRAFFIC_EXCEED`        | Traffic limit exceeded       |
| `UNAUTHORIZED`          | Authentication failed        |
| `NETWORK_ERROR`         | Network connection error     |
| `VPN_PERMISSION_DENIED` | VPN permission not granted   |
| `CONNECTION_CANCELLED`  | Connection cancelled by user |
| `INTERNAL_ERROR`        | Internal SDK error           |

### NetworkRelatedException

Exception for network-related errors.

```java
public class NetworkRelatedException extends VpnException {
    // Indicates network connectivity issues
}
```

### ConnectionCancelledException

Exception when connection is cancelled.

```java
public class ConnectionCancelledException extends VpnException {
    // Thrown when user cancels connection
}
```

## Transport Modes

### TransportMode

Enum for available VPN protocols.

| Mode          | Description             |
| ------------- | ----------------------- |
| `HYDRA_TCP`   | Hydra protocol over TCP |
| `HYDRA_UDP`   | Hydra protocol over UDP |
| `OPENVPN_TCP` | OpenVPN over TCP        |
| `OPENVPN_UDP` | OpenVPN over UDP        |
| `WIREGUARD`   | WireGuard protocol      |

## Content Filtering (CNL)

### Cnl

Interface for content filtering and blocking lists.

#### Methods

**`enableCnl(CnlConfig config, CompletableCallback callback)`**

Enables content filtering.

**Parameters:**

* `config` - CNL configuration
* `callback` - Completion callback

**`disableCnl(CompletableCallback callback)`**

Disables content filtering.

**Parameters:**

* `callback` - Completion callback

**`getCnlState(Callback<CnlState> callback)`**

Gets current CNL state.

**Parameters:**

* `callback` - Callback with CNL state

### CnlConfig

Configuration for content filtering.

```java
CnlConfig config = new CnlConfig.Builder()
    .addBlockedCategory(CnlCategory.ADULT)
    .addBlockedCategory(CnlCategory.MALWARE)
    .addCustomBlockedDomain("example.com")
    .build();
```

| Method                            | Description                 |
| --------------------------------- | --------------------------- |
| `addBlockedCategory(CnlCategory)` | Adds category to block      |
| `addCustomBlockedDomain(String)`  | Adds custom domain to block |
| `addCustomAllowedDomain(String)`  | Adds custom domain to allow |

### CnlCategory

Enum for content categories.

| Category       | Description            |
| -------------- | ---------------------- |
| `ADULT`        | Adult content          |
| `MALWARE`      | Malicious websites     |
| `PHISHING`     | Phishing sites         |
| `ADS`          | Advertisement servers  |
| `TRACKING`     | Tracking servers       |
| `GAMBLING`     | Gambling sites         |
| `SOCIAL_MEDIA` | Social media platforms |

## Fireshield Configuration

### FireshieldConfig

Advanced firewall and security configuration.

```java
FireshieldConfig config = new FireshieldConfig.Builder()
    .mode(FireshieldMode.ENABLED)
    .addService(FireshieldService.builder()
        .protocol(Protocol.TCP)
        .port(80)
        .build())
    .build();
```

| Method                          | Description                  |
| ------------------------------- | ---------------------------- |
| `mode(FireshieldMode)`          | Sets Fireshield mode         |
| `addService(FireshieldService)` | Adds service configuration   |
| `userCategories(List<Integer>)` | Sets user-defined categories |

### FireshieldMode

| Mode       | Description                |
| ---------- | -------------------------- |
| `DISABLED` | Fireshield disabled        |
| `ENABLED`  | Fireshield enabled         |
| `SILENT`   | Silent mode (logging only) |

## Migration and Compatibility

### SDK Version

```java
String version = UnifiedSdk.getVersion();
```

### Minimum Requirements

* Android API Level: 26 (Android 8.0)
* Compile SDK Version: 35
* Target SDK Version: 35

### Permissions Required

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
```

### ProGuard Rules

See [Proguard Rules](/paas/sdk/vpn-sdk-for-android/setup/configuration.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pango.gitbook.io/paas/sdk/vpn-sdk-for-android/api-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
