Skip to content

Commit 753b8d3

Browse files
authored
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 <[email protected]>
1 parent 8ff0672 commit 753b8d3

File tree

1 file changed

+15
-4
lines changed
  • android/src/main/java/com/tailscale/ipn

1 file changed

+15
-4
lines changed

android/src/main/java/com/tailscale/ipn/App.kt

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -371,16 +371,27 @@ open class UninitializedApp : Application() {
371371

372372
fun startVPN() {
373373
val intent = Intent(this, IPNService::class.java).apply { action = IPNService.ACTION_START_VPN }
374+
// FLAG_UPDATE_CURRENT ensures that if the intent is already pending, the existing intent will
375+
// be updated rather than creating multiple redundant instances.
376+
val pendingIntent =
377+
PendingIntent.getService(
378+
this,
379+
0,
380+
intent,
381+
PendingIntent.FLAG_UPDATE_CURRENT or
382+
PendingIntent.FLAG_IMMUTABLE // FLAG_IMMUTABLE for Android 12+
383+
)
384+
374385
try {
375-
startForegroundService(intent)
386+
pendingIntent.send()
376387
} catch (foregroundServiceStartException: IllegalStateException) {
377388
TSLog.e(
378389
TAG,
379-
"startVPN hit ForegroundServiceStartNotAllowedException in startForegroundService(): $foregroundServiceStartException")
390+
"startVPN hit ForegroundServiceStartNotAllowedException: $foregroundServiceStartException")
380391
} catch (securityException: SecurityException) {
381-
TSLog.e(TAG, "startVPN hit SecurityException in startForegroundService(): $securityException")
392+
TSLog.e(TAG, "startVPN hit SecurityException: $securityException")
382393
} catch (e: Exception) {
383-
TSLog.e(TAG, "startVPN hit exception in startForegroundService(): $e")
394+
TSLog.e(TAG, "startVPN hit exception: $e")
384395
}
385396
}
386397

0 commit comments

Comments
 (0)