# Integrate oneconnect SDK for Android

Current version: ![1.0.9](/files/wYWYRoosOCpBxAG80F2y)

## [​](https://jitpack.io/#AnchorFreePartner/hydra-sdk-android)OneConnect Android SDK  [Supported 16KB Page size](https://developer.android.com/guide/practices/page-sizes)

[OneConnect.top](https://oneconnect.top/) SDK is an Android library that provides easy access to OneConnect API, allowing you to retrieve server information for VPN services. You can use this library to fetch both free and premium servers for your VPN application. persistent notifications, and real-time connection stats.

***

{% content-ref url="/pages/IYIip6Rur4GCAIRnmOP6" %}
[Migration Guide From v1.1.0](/oneconnect-sdk-for-android-doc/migration-guide-from-v1.1.0.md)
{% endcontent-ref %}

### 🛠 Installation

* **Add JitPack to your root `build.gradle`:**

  ```groovy
  allprojects {
      repositories {
          ...
          maven { url "https://jitpack.io" }
      }
  }
  ```
* **Add OneConnect SDK to your app-level `build.gradle`:**

  ```groovy
  dependencies {
      implementation 'com.github.oneconnectapi:OneConnectLib:v1.1.75' //Change to latest version
  }
  ```

***

### 📋 Manifest Setup & Permissions

Add the following permissions to your `AndroidManifest.xml`:

```xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
```

> ⚠️ **Google Play Policy Note:**\
> If you publish your app, you must justify the use of `FOREGROUND_SERVICE` by submitting a video showing your app running in the background with notifications enabled.

***

### 🧩 Component Declarations

Add these to your `AndroidManifest.xml`:

```xml
<activity
    android:name="top.oneconnectapi.app.activities.DisconnectVPN"
    android:autoRemoveFromRecents="true"
    android:excludeFromRecents="true"
    android:noHistory="true"
    android:taskAffinity=".DisconnectVPN"
    android:theme="@style/blinkt.dialog" />

<service
    android:name="top.oneconnectapi.app.core.OpenVPNService"
    android:exported="true"
    android:permission="android.permission.BIND_VPN_SERVICE"
    android:foregroundServiceType="specialUse"
    android:process=":openvpn">
    <intent-filter>
        <action android:name="android.net.VpnService" />
    </intent-filter>
    <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="vpn"/>
</service>

<service
    android:name="top.oneconnectapi.app.core.keepVPNAlive"
    android:process=":openvpn"
    android:exported="true"
    android:permission="android.permission.BIND_JOB_SERVICE"/>
```

***

### 🔔 Request Notification Permission (Android 13+)

This permission is **required** for the SDK to display its persistent VPN notification correctly on Android 13 and above.

```java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
        != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
            activity,
            new String[]{Manifest.permission.POST_NOTIFICATIONS},
            1001
        );
    }
}
```

***

### 🚀 SDK Initialization & Server Fetching

Initialize the OneConnect SDK with your API key:

```java
OneConnect oneConnect = new OneConnect();
oneConnect.initialize(this, "YOUR_KEY_HERE");
```

Fetch server lists asynchronously:

```java
oneConnect.fetch(new ServerResponseListener() {
    @Override
    public void onSuccess(ArrayList<OneConnectServer> freeServersList, ArrayList<OneConnectServer> premiumServersList) {
        // Print the first free server details to Logcat
        Log.d("OneConnectServer",
                "ID: " + freeServersList.get(0).getId() +
                ", Name: " + freeServersList.get(0).getServerName() +
                ", Country: " + freeServersList.get(0).getCountry() +
                ", Username: " + freeServersList.get(0).getVpnUserName() +
                ", Configuration: " + freeServersList.get(0).getOvpnConfiguration());
    }

    @Override
    public void onFailure(Exception e) {
        Log.e("OneConnectServer", "Failed to fetch servers", e);
    }
});
```

> The `onSuccess`callback returns two `ArrayList<OneConnectServer>` objects:
>
> * `freeServersList`: list of free servers
> * `premiumServersList`: list of premium servers

#### Additonally:

You can fetch the raw JSON string instead:

```java
oneConnect.fetchJson(new JsonResponseListener() {
    @Override
    public void onSuccess(String freeServersJson, String premiumServersJson) {
        //Parse freeServersJson or premiumServersJson to use
    }

    @Override
    public void onFailure(Exception e) {
        Log.e("OneConnectServer", "Failed to fetch servers", e);
    }
});
```

#### Sample JSON response

```json
[
  {
    "id":"402",
    "serverName":"US-St Louis",
    "ovpnConfiguration":"OPENVPN CONFIGURATION",
    "country":"United States",
    "flag_url":"https://raw.githubusercontent.com/oneconnectapi/flag-sdk/main/us.png",
    "vpnUserName":"USERNAME",
    "vpnPassword":"PASSWORD"
  }
]
```

***

### 🔐 VPN Connection Flow

#### Request VPN permission (Connection request):

```java
Intent intent = VpnService.prepare(this);
if (intent != null) {
    startActivityForResult(intent, 1234);
} else {
    //Start your connection flow here if given permission already   
    startVpnConnection();
}
```

#### Handle result:

```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1234 && resultCode == RESULT_OK) {
        //Start your connection flow here if first time connecting
        startVpnConnection();
    } else {
        Log.e("OneConnectVPN", "User denied VPN permission");
    }
}
```

#### Start VPN:

```java
private void startVpnConnection() {
    String config = ...;     //from OneConnect e.g. freeServersList.get(0).getOvpnConfiguration()
    String title = "Japan"; //Notification title e.g. freeServersList.get(0).getServerName()
    String userName = ...;   //from OneConnect e.g. freeServersList.get(0).getVpnUserName()
    String passWord = ...;   //from OneConnect e.g. freeServersList.get(0).getVpnPassword()

    OpenVpnApi.startVpn(this, config, title, userName, passWord);
}
```

***

### 🛑 Stopping the VPN

#### With confirmation dialog:

```java
Intent intent = new Intent(getContext(), DisconnectVPN.class);
startActivity(intent);
```

#### Silent disconnect:

```java
Intent intent = new Intent(getContext(), DisconnectVPN.class);
intent.putExtra("instantStop", true);
startActivity(intent);
```

***

### 📡 VPN Status Monitoring

To receive real-time VPN connection stats from the OneConnect SDK, you **must register a BroadcastReceiver** for the `top.oneconnectapi.app.VPN_STATS` intent. These stats are emitted by the SDK during an active VPN session and can be used to update your VPN UI with live connection data.

#### Register receiver:

```java
IntentFilter filter = new IntentFilter("top.oneconnectapi.app.VPN_STATS");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    registerReceiver(broadcastReceiver, filter, Context.RECEIVER_EXPORTED);
} else {
    registerReceiver(broadcastReceiver, filter);
}
```

#### Handle stats:

```java
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            setStatus(intent.getStringExtra("state"), true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String duration = intent.getStringExtra("duration");
            String lastPacketReceive = intent.getStringExtra("lastPacketReceive");
            String byteIn = intent.getStringExtra("byteIn");
            String byteOut = intent.getStringExtra("byteOut");

            if (duration == null) duration = "00:00:00";
            if (lastPacketReceive == null) lastPacketReceive = "0";
            if (byteIn == null) byteIn = "wait";
            if (byteOut == null) byteOut = "wait";

            updateConnectionStatus(duration, lastPacketReceive, byteIn, byteOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
```

> These stats are ideal for updating your VPN UI with connection duration, traffic usage, and last packet timing. You can display them in your app’s status screen.

#### Unregister receiver:

```java
@Override
public void onDestroy() {
    super.onDestroy();

    if (broadcastReceiver != null) {
        try {
            unregisterReceiver(broadcastReceiver);
            Log.d("ReceiverLifecycle", "broadcastReceiver unregistered");
        } catch (IllegalArgumentException e) {
            Log.w("ReceiverLifecycle", "broadcastReceiver not registered: " + e.getMessage());
        }
        broadcastReceiver = null;
    }
}
```

> Don't forget to unregister the receiver when it's no longer needed (e.g. in onDestroy()) to avoid memory leaks and unintended behavior.

***

###

\
In the code snippet above:

## Ready demo project

Here we have ready demo project , you can frog from GitHub and use

{% embed url="<https://github.com/oneconnectapi/OneConnectSdk-demo-android>" %}

**Usage**

This SDK Project is Created By OneConnect Team.

#### This Project Content OneConnect Library

#### For Use, the SDK Required OneConnect API Key,

Visit on this Website <https://developer.oneconnect.top> and Create Account and get the Key.

#### Once You have the OneConnect API Key, Then You have Put inside SplashScreen.java

You will Get the Key inside API Tab <https://developer.oneconnect.top/dashboard/api/> After that, You need to Put Your App Package Name Inside OneConnect API Tab.

<figure><img src="/files/0epu6ufyESNtvpdUBIim" alt=""><figcaption></figcaption></figure>

#### You have to Put inside SplashScreen.java Please See Screenshot

![](https://oneconnect.top/serverkey.png)

\# This Project Content AdMob & Facebook Ads those developers want to Add Another Ads SDK they need to follow the Exiting Method of Ads SDK and Also Have IAP Subscription.

#### And Need to Put Your Google-Services.JSON file inside Project, You will get from Firebase.

#### Note :- Any Developer, those who want to Use or Sell for end Client

they need to make the sufficient Changes in the Original Demo Project.

## Just Smile after get the Project..... **(^\_^)**

####


---

# Agent Instructions: 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://oneconnect-1.gitbook.io/oneconnect-sdk-for-android-doc/integrate-oneconnect-sdk-for-android.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.
