From 753b8d3fb4b34b65b01a3b0ea0c227c3ba341ad8 Mon Sep 17 00:00:00 2001 From: kari-ts <135075563+kari-ts@users.noreply.github.com> Date: Thu, 10 Oct 2024 16:27:25 -0700 Subject: [PATCH] android: handle multiple redundant intents (#541) Use FLAG_UPDATE_CURRENT for managing multiple calls to startForegroundService. This ensures only one instance of the intent is active and replaces any previously pending intents with the latest one. Fixes tailscale/corp#23828 Signed-off-by: kari-ts --- .../src/main/java/com/tailscale/ipn/App.kt | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/android/src/main/java/com/tailscale/ipn/App.kt b/android/src/main/java/com/tailscale/ipn/App.kt index dd89972..f0b3dde 100644 --- a/android/src/main/java/com/tailscale/ipn/App.kt +++ b/android/src/main/java/com/tailscale/ipn/App.kt @@ -371,16 +371,27 @@ open class UninitializedApp : Application() { fun startVPN() { val intent = Intent(this, IPNService::class.java).apply { action = IPNService.ACTION_START_VPN } + // FLAG_UPDATE_CURRENT ensures that if the intent is already pending, the existing intent will + // be updated rather than creating multiple redundant instances. + val pendingIntent = + PendingIntent.getService( + this, + 0, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or + PendingIntent.FLAG_IMMUTABLE // FLAG_IMMUTABLE for Android 12+ + ) + try { - startForegroundService(intent) + pendingIntent.send() } catch (foregroundServiceStartException: IllegalStateException) { TSLog.e( TAG, - "startVPN hit ForegroundServiceStartNotAllowedException in startForegroundService(): $foregroundServiceStartException") + "startVPN hit ForegroundServiceStartNotAllowedException: $foregroundServiceStartException") } catch (securityException: SecurityException) { - TSLog.e(TAG, "startVPN hit SecurityException in startForegroundService(): $securityException") + TSLog.e(TAG, "startVPN hit SecurityException: $securityException") } catch (e: Exception) { - TSLog.e(TAG, "startVPN hit exception in startForegroundService(): $e") + TSLog.e(TAG, "startVPN hit exception: $e") } }