当您想启动 Vpn 时,我们可以这样做:
VpnService.prepare(activity)
然后 :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_VPN && resultCode == AppCompatActivity.RESULT_OK) {
}
}
}
但我们是在活动之外做的,我是这样做的:
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();
}
}
}
}
所以基本上我正在等待 VPN 准备好而没有任何指示,这是可行的,但感觉不是一个好习惯,当 VPN 准备好时,还有其他方法可以收听吗?某种监听器?