Connecting to a VPN in MainActivity.kt (Kotlin)

Viewed 953

Is there a simple way to connect to a VPN using VpnService from Android Studio (Kotlin)? I have read the developer.android.com documentation, but as a new Kotlin developer, I am very confused. I know that there is a Sample VPN app (ToyVPN), but the implementation is spread throughout multiple files.

I am looking for a simple way to easily connect to a VPN from MainActivity.kt.

Update: The solution can be spread out through multiple external files. As long as I can call it from MainActivity.kt, it will be good.

Here is a sample of what I would like to achieve:

package com.example.notekeeperlearnas


import android.app.Activity
import android.content.Intent
import android.net.VpnService
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.content_main.*


class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(findViewById(R.id.toolbar))


        toggleButton.setOnCheckedChangeListener({ buttonView, isChecked ->
            // Call a function to connect to a VPN
            Snackbar.make(
                buttonView, "Connecting to VPN: $isChecked",
                Snackbar.LENGTH_LONG
            )
                .show()
        })
    }
}
0 Answers
Related