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 <kari@tailscale.com>
pull/543/head
kari-ts 2 months ago committed by GitHub
parent 8ff0672ec7
commit 753b8d3fb4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -371,16 +371,27 @@ open class UninitializedApp : Application() {
fun startVPN() { fun startVPN() {
val intent = Intent(this, IPNService::class.java).apply { action = IPNService.ACTION_START_VPN } 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 { try {
startForegroundService(intent) pendingIntent.send()
} catch (foregroundServiceStartException: IllegalStateException) { } catch (foregroundServiceStartException: IllegalStateException) {
TSLog.e( TSLog.e(
TAG, TAG,
"startVPN hit ForegroundServiceStartNotAllowedException in startForegroundService(): $foregroundServiceStartException") "startVPN hit ForegroundServiceStartNotAllowedException: $foregroundServiceStartException")
} catch (securityException: SecurityException) { } catch (securityException: SecurityException) {
TSLog.e(TAG, "startVPN hit SecurityException in startForegroundService(): $securityException") TSLog.e(TAG, "startVPN hit SecurityException: $securityException")
} catch (e: Exception) { } catch (e: Exception) {
TSLog.e(TAG, "startVPN hit exception in startForegroundService(): $e") TSLog.e(TAG, "startVPN hit exception: $e")
} }
} }

Loading…
Cancel
Save