2

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()
        })
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • It sounds like you are not aware that VpnService does not actually implement any VPN protocol/service. It only provides the facilities an app can use (via a subclass) to implement this itself (hence the amount of code even in the ToyVPN example). – ecdsa Jul 06 '20 at 08:03
  • Thanks for clarifying! I've updated my question to allow for a broader answer. –  Jul 06 '20 at 14:09
  • Please don't tag questions with the android-studio tag just because you use it: the Android Studio tag should **only** be used when you have questions about the IDE itself, and not any code you write (or want to write) in it. See [when is it appropriate to remove an IDE tag](https://meta.stackoverflow.com/a/315196/6296561), [How do I avoid misusing tags?](https://meta.stackoverflow.com/q/354427/6296561), and [the tagging guide](/help/tagging). Use [android] or other relevant tags instead. – Zoe Jul 06 '20 at 14:12
  • Okay. Thanks for removing it! –  Jul 06 '20 at 14:13

0 Answers0