Disconnect any VPN service programmatically

Viewed 677

I am trying to find a way to disconnect any VPN which is connected now by other applications.

1- Is there a way to do this?

2- Is there a way to reconnect the last VPN after disconnecting it?

Note(My thoughts): When our app tries to turn vpn on, If there is another vpn running, it will be terminated and our vpn will be turned on. So after this, we can turn our vpn service off (SUCCESS). If this is right, can anybody show me how to do the above scenario?

1 Answers

I found an answer for the first part but the second one needs help:

class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_empty)
        checkVPN()
    }

    private fun checkVPN() {
        val intent = VpnService.prepare(applicationContext)
        if (intent != null) {
            startActivityForResult(intent, 0)
        } else {
            onActivityResult(0, RESULT_OK, null)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == RESULT_OK) {
            val intent = Intent(this, BackgroundService::class.java)
            startServiceCompat(intent)
        }
    }
}

This disconnects any connected vpn and for the first time, it asks user to connect vpn but we do not connect any vpn after this.

Related