How to know when Android VPN prepare is ready without Activity?

537 Views Asked by At

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?

0

There are 0 best solutions below