vpn: retry connect after VPN permission grant via Activity Result API
- Commit
18aa4543ecc8146a0989ac46c046d4b40f7aee5a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-08 02:46 UTC (28 days ago)
- Parents
704447e
VpnViewModel.startVpn() fired the system VPN-consent intent with the deprecated Activity.startActivityForResult() and handled no result, so a first-time user who tapped Connect and granted permission was left on a 'Granting VPN permission...' snackbar with the tunnel never starting; they had to tap Connect a second time. The request code constant had no matching onActivityResult anywhere in the app (MainActivity and ConfigListPage contain no result handling), which reading the call path confirms: ConfigListPage is the only startVpn caller and only passes its activity through. Split the permission step from the connect step: startVpn(config, onPermissionNeeded) hands the VpnService.prepare() consent intent to the caller instead of firing it, and connects directly when prepare() returns null. ConfigListPage launches the consent intent through a StartActivityForResult launcher; on RESULT_OK it retries startVpn with the same config (which now connects), and on denial the VM reports 'VPN permission denied' instead of hanging on the granting status. This also drops the deprecated startActivityForResult call. Update FinalVpnBatchTest.viewModelStartVpnAsksPermission to the new signature: it asserts the consent intent is handed out, the granting status is set, and the denial path reports its status. Verified with :vpn:testDevUnitTest (112 tests, 0 failures).
Diff
vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.ktindex 1a5f1af3b7..560dc7b5f9 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt@@ -1,6 +1,5 @@ package com.vayunmathur.vpn.platform -import android.app.Activity import android.app.Application import android.content.Context import android.content.Intent@@ -94,12 +93,21 @@ class VpnViewModel( } } - fun startVpn(activity: Activity, config: VpnConfig) {+ /**+ * Connects [config], requesting system VPN consent first when needed.+ *+ * When [VpnService.prepare] returns a consent intent, the tunnel cannot+ * start yet: the intent is handed to [onPermissionNeeded] so the caller+ * can launch it through the Activity Result API, and the caller retries+ * this same method after the user grants consent (at which point+ * prepare() returns null and the tunnel starts directly).+ */+ fun startVpn(config: VpnConfig, onPermissionNeeded: (Intent) -> Unit) { val ctx = getApplication<Application>()- val intent = VpnService.prepare(ctx)- if (intent != null) {- activity.startActivityForResult(intent, VPN_PERMISSION_REQUEST)+ val permissionIntent = VpnService.prepare(ctx)+ if (permissionIntent != null) { _status.value = "Granting VPN permission…"+ onPermissionNeeded(permissionIntent) return } viewModelScope.launch(Dispatchers.IO) {@@ -116,6 +124,10 @@ class VpnViewModel( } } + fun onVpnPermissionDenied() {+ _status.value = "VPN permission denied"+ }+ fun stopVpn() { val ctx = getApplication<Application>() val svcIntent = Intent(ctx, VpnTunnelService::class.java).apply {@@ -215,7 +227,6 @@ class VpnViewModel( companion object { private const val STOP_TIMEOUT_MS = 5_000L private const val POLL_RUNNING_MS = 500L- private const val VPN_PERMISSION_REQUEST = 1001 } }
vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.ktindex 8f9f4d927c..8f6f3eeaf2 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt@@ -1,20 +1,24 @@ package com.vayunmathur.vpn.ui import android.app.Activity+import android.content.Intent import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.ui.SnackbarHostState import com.vayunmathur.vpn.R import com.vayunmathur.vpn.Route+import com.vayunmathur.vpn.data.VpnConfig import com.vayunmathur.vpn.service.VpnTunnelService import com.vayunmathur.vpn.platform.VpnViewModel import kotlinx.coroutines.launch@@ -30,6 +34,24 @@ fun ConfigListPage(backStack: NavBackStack<Route>, vm: VpnViewModel) { val scope = rememberCoroutineScope() val needActivityMsg = stringResource(R.string.need_activity_to_grant_vpn_permission) + // System VPN consent runs through the Activity Result API: when the user+ // grants permission the same config is retried, which then connects+ // directly (previously the grant went nowhere and the user had to tap+ // Connect a second time).+ var pendingConfig by remember { mutableStateOf<VpnConfig?>(null) }+ lateinit var launchPermission: (Intent) -> Unit+ val permissionLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ val granted = pendingConfig+ pendingConfig = null+ if (result.resultCode == Activity.RESULT_OK && granted != null) {+ vm.startVpn(granted, launchPermission)+ } else {+ vm.onVpnPermissionDenied()+ }+ }+ launchPermission = permissionLauncher::launch // The only way to add a tunnel is opening a .conf file via SAF. val filePicker = rememberLauncherForActivityResult( contract = ActivityResultContracts.OpenDocument(),@@ -54,8 +76,10 @@ fun ConfigListPage(backStack: NavBackStack<Route>, vm: VpnViewModel) { if (connectingId != null && VpnTunnelService.isRunning) { vm.stopVpn() } else {- if (activity != null) vm.startVpn(activity, cfg)- else scope.launch {+ if (activity != null) {+ pendingConfig = cfg+ vm.startVpn(cfg, permissionLauncher::launch)+ } else scope.launch { snackbar.showSnackbar(needActivityMsg) } }
vpn/src/test/java/com/vayunmathur/vpn/ui/FinalVpnBatchTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/ui/FinalVpnBatchTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/ui/FinalVpnBatchTest.ktindex a33ade1142..587d656487 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/ui/FinalVpnBatchTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/ui/FinalVpnBatchTest.kt@@ -22,6 +22,7 @@ import com.vayunmathur.vpn.ui.components.AppIconImage import com.vayunmathur.vpn.ui.components.LockdownWarning import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking@@ -110,15 +111,17 @@ class FinalVpnBatchTest { Unit } } - @Test fun viewModelStartVpnWithActivityAsksPermission() {+ @Test fun viewModelStartVpnAsksPermission() { val dao = VpnViewModelTest.FakeConfigDao() val vm = VpnViewModel(app, dao, VpnViewModelTest.FakeLogDao())- vm.startVpn(rule.activity, com.vayunmathur.vpn.data.VpnConfig(id = 4, name = "PermTun"))+ var asked: android.content.Intent? = null+ vm.startVpn(com.vayunmathur.vpn.data.VpnConfig(id = 4, name = "PermTun")) { asked = it } // Robolectric's VpnService.prepare returns a consent intent, so the VM must- // ask for permission instead of starting the service.- assertTrue(- vm.status.value?.contains("Granting") == true || Shadows.shadowOf(rule.activity).nextStartedActivityForResult != null,- "status=${vm.status.value}",- )+ // hand it out for the Activity Result launcher instead of starting the service.+ assertNotNull(asked, "status=${vm.status.value}")+ assertTrue(vm.status.value?.contains("Granting") == true, "status=${vm.status.value}")+ // A denied grant surfaces a status instead of hanging on "Granting…".+ vm.onVpnPermissionDenied()+ assertEquals("VPN permission denied", vm.status.value) } }