1

When you want to start Vpn we can do :

VpnService.prepare(activity)

Then :

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_VPN && resultCode == AppCompatActivity.RESULT_OK) {
 
        }

    }
}

But we i do it out side of the activity i do it like that :

private void setupVPN() {
     if (vpnInterface == null) {

         jni_context = jni_init(Build.VERSION.SDK_INT);
        Builder builder = new Builder();
        builder.addAddress(VPN_ADDRESS, 1);

        vpnInterface = getBuilder().establish();//.setSession(getString(R.string.app_name)).setConfigureIntent(pendingIntent).establish();

        if (vpnInterface != null) {
             startNative();
        } else {
            // vpn failed to establish, prepare may not call or called but not yey prepared,
            // we will try 3 times or destroy vpn
            Timber.e("vpnInterface failed to establish");
            vpnSetupAttempts++;
            if (vpnSetupAttempts < 4) {
                VpnService.prepare(this);
                final Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(this::setupVPN, 2000);
            } else {
                vpnSetupAttempts = 0;
                logNonFatalException("vpnInterface failed to establish");
                stopVpn();

            }
        }

    }
}

So basically i"m waiting for VPN to be prepared without indication, This is working but not feel like a good practice, is there any other method that is possible to listen when the VPN is prepared? some kind of listener?

Jesus Dimrix
  • 4,378
  • 4
  • 28
  • 62
  • `prepare()` creates an Intent, which you then have to start so the user can grant permission to the app to act as a VPN (no Intent is returned if that permission was granted previously). I don't see you handling that return value. – ecdsa Sep 30 '20 at 13:39
  • I"m assuming permission rmision already granted in this scenario – Jesus Dimrix Oct 01 '20 at 14:13
  • So why call it then? – ecdsa Oct 01 '20 at 14:16
  • To activate vpn if cases it is destroyed,like when application restart or for some reason von crashed, or re activate after pause – Jesus Dimrix Oct 01 '20 at 14:22

0 Answers0