Skip to content

Colota - Android GPS Location tracker

fix(profiles): keep the deactivation delay when a lower-priority profile matches (#885)

Max Dietrich61e52f7f7c82
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 649ba494..f0a8f9e9 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -75,7 +75,7 @@ Each profile overrides the default tracking configuration with:
- **Sync interval** - How often to sync with the server (Instant, 1 min, 5 min, 15 min, or Custom)
- **Priority** - Determines which profile wins when multiple conditions match simultaneously (higher wins; equal numbers go to the older profile)
- **Activation Delay** - How long the condition must keep matching before the profile is applied (seconds, default 0 = immediate). Prevents activating on brief spikes, e.g. a momentary speed reading. For the Stationary condition it instead sets how long the device must be still before the profile activates (default 60s).
-- **Deactivation Delay** - How long to wait after the condition stops matching before reverting to default settings (seconds). Prevents rapid toggling when conditions fluctuate.
+- **Deactivation Delay** - How long the profile stays active after its condition stops matching, also when a lower-priority profile matches (seconds). Prevents rapid toggling when conditions fluctuate.
When creating a new profile, the tracking interval, movement threshold and sync interval are pre-filled with your current Tracking & sync values, and each field says which value it replaces. The values a profile hands back to are the ones the service loaded when tracking started; a Tracking & sync change applies at the next restart.
@@ -107,9 +107,9 @@ Note that Stationary has the highest priority so it takes over from Walking when
- When tracking starts, all enabled profiles are evaluated against current conditions
- The highest-priority matching profile's settings override the defaults
- If a profile has an activation delay, its condition must keep matching for that long before it is applied; if the condition drops first, or a higher-priority profile takes over, the activation is cancelled
-- When the condition no longer matches, a deactivation delay timer starts
-- If the condition matches again before the delay expires, the timer is cancelled
-- After the delay expires, settings revert to the defaults configured in the Settings screen
+- When the condition no longer matches, a deactivation delay timer starts, also when a lower-priority profile matches
+- If the condition matches again before the delay expires, the timer is cancelled. A higher-priority profile that matches still takes over as soon as its own activation delay has passed
+- After the delay expires, the highest-priority matching profile takes over once its activation delay has passed. Until then, or if nothing matches, settings revert to the defaults configured in the Settings screen
- Profile changes made in the editor take effect immediately on the running service
- **Tracking & sync** shows the active profile above the Recording and Sync interval groups with the values in force. The rows below are the defaults the profile is overriding
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
index de6a18b1..a55f7ade 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
@@ -15,7 +15,8 @@ import kotlinx.coroutines.*
*
* When a profile's conditions match, its GPS interval / sync settings override
* the default config. When conditions stop matching, a configurable deactivation
- * delay (hysteresis) prevents rapid switching before reverting to defaults.
+ * delay (hysteresis) prevents rapid switching before handing over to the next
+ * matching profile or the defaults.
*
* @param profileHelper CRUD access to profile database
* @param scope Coroutine scope for deactivation delay timers
@@ -45,28 +46,24 @@ class ProfileManager(
@Volatile var defaultDistance: Float = 0f
@Volatile var defaultSyncInterval: Int = 0
- // Active profile: mutated only inside @Synchronized methods.
- // @Volatile because getActiveProfileName() is read externally without the lock.
+ // @Volatile: getActiveProfileName() reads it without the lock.
@Volatile private var activeProfile: ProfileHelper.CachedProfile? = null
- // Accessed only inside @Synchronized methods — the intrinsic lock covers visibility.
+ // Guarded by the @Synchronized methods.
private var deactivationJob: Job? = null
private var activationJob: Job? = null
private var pendingActivationProfileId: Int? = null
+ private var deferredActivationProfileId: Int? = null
- // Condition flags: written from broadcast callbacks, each write immediately followed by
- // @Synchronized evaluate() which reads them. @Volatile makes the write visible to readers
- // already holding the lock on another thread.
+ // Written outside the lock, read by evaluate() under it.
@Volatile private var isCharging = false
@Volatile private var isCarMode = false
@Volatile var isStationary = false
private set
- // The run of consecutive sub-threshold fixes, timed by location.time.
- // Written/read from location + motion callbacks without synchronization.
+ // The current still run, timed by location.time and written without the lock.
@Volatile private var runStartedAtMs = 0L
@Volatile private var lastSampleAtMs = 0L
@Volatile private var lastSampleGapMs = 0L
- // Speed rolling average buffer
private val speedBuffer = ArrayDeque<Float>()
private val speedLock = Any()
@@ -114,21 +111,18 @@ class ProfileManager(
fun getNeededConditionTypes(): Set<String> =
profileHelper.getEnabledProfiles().mapTo(HashSet()) { it.conditionType }
- /**
- * Re-evaluates all enabled profiles against current conditions.
- * Must handle concurrent calls from location updates, broadcasts, and service actions.
- */
@Synchronized
fun evaluate() {
val profiles = profileHelper.getEnabledProfiles()
- // If the active profile was disabled or deleted, deactivate immediately (no delay)
+ // A disabled or deleted profile skips its deactivation delay.
if (activeProfile != null && profiles.none { it.id == activeProfile!!.id }) {
cancelDeactivation()
deactivateToDefault()
}
- if (pendingActivationProfileId != null && profiles.none { it.id == pendingActivationProfileId }) {
+ val waitingProfileId = pendingActivationProfileId ?: deferredActivationProfileId
+ if (waitingProfileId != null && profiles.none { it.id == waitingProfileId }) {
cancelActivation()
}
@@ -136,17 +130,14 @@ class ProfileManager(
return
}
- // Find highest-priority matching profile (list already sorted by priority DESC)
+ // getEnabledProfiles is sorted by priority DESC, id ASC.
val matchingProfile = profiles.firstOrNull { matchesCondition(it) }
when {
- // A profile matches — activate it (or keep if already active)
matchingProfile != null -> {
- cancelDeactivation()
-
if (activeProfile?.id == matchingProfile.id) {
+ cancelDeactivation()
cancelActivation()
- // Same profile still matches — re-apply only if config changed
val active = activeProfile!!
if (active.intervalMs != matchingProfile.intervalMs ||
active.minUpdateDistance != matchingProfile.minUpdateDistance ||
@@ -156,12 +147,13 @@ class ProfileManager(
return
}
- // Stationary spends its activation delay reaching the stationary state, so it
- // applies immediately here; the generic delay would double-count it.
- val activationDelay =
- if (matchingProfile.conditionType == ProfileConstants.CONDITION_STATIONARY) 0
- else matchingProfile.activationDelaySeconds
- if (activationDelay <= 0) {
+ val active = activeProfile
+ if (active != null && ranksAbove(profiles, active.id, matchingProfile.id)) {
+ holdForDeactivation(active, matchingProfile)
+ return
+ }
+
+ if (isActivationSatisfied(matchingProfile)) {
cancelActivation()
activateProfile(matchingProfile)
} else {
@@ -169,19 +161,53 @@ class ProfileManager(
}
}
- // No profile matches — schedule deactivation if one was active
activeProfile != null -> {
cancelActivation()
scheduleDeactivation(activeProfile!!)
}
- // Pending activation's condition dropped before its delay elapsed
else -> {
cancelActivation()
}
}
}
+ /** The active profile stopped matching and a lower one matches: each delay runs on its own condition. */
+ private fun holdForDeactivation(active: ProfileHelper.CachedProfile, next: ProfileHelper.CachedProfile) {
+ if (active.deactivationDelaySeconds <= 0) {
+ cancelDeactivation()
+ handOver(next)
+ return
+ }
+ scheduleDeactivation(active)
+ if (!isActivationSatisfied(next)) scheduleActivation(next)
+ else if (deferredActivationProfileId != next.id) cancelActivation()
+ }
+
+ private fun handOver(next: ProfileHelper.CachedProfile?) {
+ if (next != null && isActivationSatisfied(next)) {
+ cancelActivation()
+ activateProfile(next)
+ } else {
+ deactivateToDefault()
+ if (next != null) scheduleActivation(next)
+ }
+ }
+
+ /**
+ * True for a delay of 0, for one that ran out while a higher profile finished its deactivation delay, and for
+ * Stationary, which spends its activation delay reaching the stationary state.
+ */
+ private fun isActivationSatisfied(profile: ProfileHelper.CachedProfile): Boolean =
+ profile.conditionType == ProfileConstants.CONDITION_STATIONARY ||
+ profile.activationDelaySeconds <= 0 ||
+ deferredActivationProfileId == profile.id
+
+ private fun ranksAbove(profiles: List<ProfileHelper.CachedProfile>, higherId: Int, lowerId: Int): Boolean {
+ val higher = profiles.indexOfFirst { it.id == higherId }
+ return higher >= 0 && higher < profiles.indexOfFirst { it.id == lowerId }
+ }
+
private fun matchesCondition(profile: ProfileHelper.CachedProfile): Boolean {
val result = when (profile.conditionType) {
ProfileConstants.CONDITION_CHARGING -> isCharging
@@ -229,14 +255,12 @@ class ProfileManager(
}
private fun activateProfile(profile: ProfileHelper.CachedProfile) {
+ cancelDeactivation()
activeProfile = profile
AppLogger.i(TAG, "Activated profile: ${profile.name} (interval=${profile.intervalMs}ms, sync=${profile.syncIntervalSeconds}s)")
- // Notify JS
LocationServiceModule.sendProfileSwitchEvent(profile.name, profile.id)
-
- // Apply config
onConfigSwitch(ProfileConfig(
interval = profile.intervalMs,
distance = profile.minUpdateDistance,
@@ -261,15 +285,15 @@ class ProfileManager(
}
/**
- * Called from the deactivation coroutine. Re-checks under lock that the
- * profile being deactivated is still the active one — prevents a race
- * where evaluate() activated a new profile between ensureActive() and
- * acquiring the synchronized lock.
+ * Runs when the deactivation delay ends. The re-check covers evaluate() switching profile between
+ * ensureActive() and the lock. The top match then takes over if its activation delay has passed, else the defaults.
*/
@Synchronized
private fun deactivateIfStillActive(scheduledProfileId: Int) {
if (activeProfile?.id != scheduledProfileId) return
- deactivateToDefault()
+ val next = profileHelper.getEnabledProfiles().firstOrNull { matchesCondition(it) }
+ if (next?.id == scheduledProfileId) return
+ handOver(next)
}
private fun cancelDeactivation() {
@@ -293,22 +317,28 @@ class ProfileManager(
}
/**
- * Called from the activation coroutine. Re-resolves the highest-priority match
- * under the lock and activates only if the scheduled profile is still the winner —
- * the condition may have lapsed or a higher-priority profile may have arrived
- * during the delay.
+ * Runs when the activation delay ends and applies the profile only if it is still the best match.
+ * A higher profile inside its deactivation delay keeps the slot until that delay ends.
*/
@Synchronized
private fun activateIfStillMatching(scheduledProfileId: Int) {
- // Superseded by a newer activation between the delay and the lock: leave its
- // job/pending fields intact rather than orphaning the newer timer.
+ // Superseded by a newer timer after the delay: leave its fields alone.
if (pendingActivationProfileId != scheduledProfileId) return
activationJob = null
pendingActivationProfileId = null
- val matching = profileHelper.getEnabledProfiles().firstOrNull { matchesCondition(it) }
+ val profiles = profileHelper.getEnabledProfiles()
+ val matching = profiles.firstOrNull { matchesCondition(it) }
if (matching?.id != scheduledProfileId) return
if (activeProfile?.id == scheduledProfileId) return
+ val active = activeProfile
+ if (active != null && deactivationJob?.isActive == true &&
+ ranksAbove(profiles, active.id, scheduledProfileId)
+ ) {
+ deferredActivationProfileId = scheduledProfileId
+ AppLogger.d(TAG, "'${matching.name}' waits for '${active.name}' to finish its deactivation delay")
+ return
+ }
activateProfile(matching)
}
@@ -316,6 +346,7 @@ class ProfileManager(
activationJob?.cancel()
activationJob = null
pendingActivationProfileId = null
+ deferredActivationProfileId = null
}
/** Only the fix that completes the window can conclude stillness; a stopped stream never does. */
@@ -384,10 +415,7 @@ class ProfileManager(
AppLogger.i(TAG, "Deactivated profile: ${previousProfile.name} - reverting to defaults")
- // Notify JS
LocationServiceModule.sendProfileSwitchEvent(null, null)
-
- // Revert to default config
onConfigSwitch(ProfileConfig(
interval = defaultInterval,
distance = defaultDistance,
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
index 6093f559..1e996fe0 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
@@ -655,7 +655,7 @@ class ProfileManagerTest {
}
@Test
- fun `applies new tracking interval when switching between profiles`() = runTest {
+ fun `applies new tracking interval when switching between profiles`() = testScope.runTest {
val charging = chargingProfile(id = 1, intervalMs = 10000, priority = 10)
val carMode = carModeProfile(id = 2, intervalMs = 3000, priority = 20)
every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
@@ -674,12 +674,288 @@ class ProfileManagerTest {
assertEquals(5f, switchedDistance, 0.01f)
assertEquals(60, switchedSyncInterval)
- // Disable car mode - charging still active, falls back immediately
+ // Disable car mode - charging applies once car mode's deactivation delay has run
manager.onCarModeStateChanged(false)
+ advanceTimeBy(31_000)
assertEquals("Charging", switchedProfileName)
assertEquals(10000L, switchedInterval)
}
+ // --- Handing over to a lower-priority profile ---
+
+ /** A deactivation delay exists to ride out a brief drop, so a lower match must not cut it short. */
+ @Test
+ fun `a lower-priority match waits out the active profile's deactivation delay`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(29_000)
+ assertEquals("Car Mode", switchedProfileName)
+ assertEquals(switches, switchCount)
+
+ advanceTimeBy(2_000)
+ assertEquals("Charging", switchedProfileName)
+ assertEquals("one switch, no defaults in between", switches + 1, switchCount)
+ }
+
+ /** Android Auto can end a moment before the cable comes out; the target is whatever matches when the delay ends. */
+ @Test
+ fun `the handover goes to what still matches when the delay ends`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(1_000)
+ manager.onChargingStateChanged(false)
+ advanceTimeBy(30_000)
+
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ assertEquals("Charging never applied", switches + 1, switchCount)
+ }
+
+ @Test
+ fun `a higher-priority match still takes over at once during the delay`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ val fast = speedAboveProfile(id = 3, threshold = 10f, priority = 30)
+ every { profileHelper.getEnabledProfiles() } returns listOf(fast, carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ manager.onCarModeStateChanged(false)
+
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+ assertEquals("Fast", switchedProfileName)
+
+ manager.clearSpeedBuffer()
+ advanceTimeBy(29_000)
+ assertEquals("Fast runs its own delay, not Car Mode's", "Fast", switchedProfileName)
+ advanceTimeBy(2_000)
+ assertEquals("Charging", switchedProfileName)
+ }
+
+ /** A higher profile that activates on its timer ends the old delay, so its own delay runs when it stops matching. */
+ @Test
+ fun `a higher profile activated by its timer gets its own deactivation delay`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ val fast = speedAboveProfile(id = 3, threshold = 10f, priority = 30, activationDelay = 10)
+ every { profileHelper.getEnabledProfiles() } returns listOf(fast, carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(1_000)
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+ advanceTimeBy(11_000)
+ assertEquals("Fast", switchedProfileName)
+
+ manager.clearSpeedBuffer()
+ advanceTimeBy(29_000)
+ assertEquals("Fast", switchedProfileName)
+ advanceTimeBy(2_000)
+ assertEquals("Charging", switchedProfileName)
+ }
+
+ /** An activation delay counts continuous matching, so a timer from an earlier match must not carry over. */
+ @Test
+ fun `a higher profile that stops matching has to wait out its full activation delay again`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ val fast = speedAboveProfile(id = 3, threshold = 10f, priority = 30, activationDelay = 10)
+ every { profileHelper.getEnabledProfiles() } returns listOf(fast, carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ manager.onCarModeStateChanged(false)
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+ advanceTimeBy(2_000)
+ manager.clearSpeedBuffer()
+ advanceTimeBy(6_000)
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+
+ advanceTimeBy(9_000)
+ assertEquals("only 9s of the second match", "Car Mode", switchedProfileName)
+ advanceTimeBy(2_000)
+ assertEquals("Fast", switchedProfileName)
+ }
+
+ @Test
+ fun `a flapping higher profile does not stretch the deactivation delay`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ val fast = speedAboveProfile(id = 3, threshold = 10f, priority = 30, activationDelay = 10)
+ every { profileHelper.getEnabledProfiles() } returns listOf(fast, carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ manager.onCarModeStateChanged(false)
+ repeat(5) {
+ advanceTimeBy(1_000)
+ repeat(ProfileConstants.SPEED_BUFFER_SIZE) {
+ manager.onLocationUpdate(mockLocation(15f))
+ }
+ advanceTimeBy(4_000)
+ manager.clearSpeedBuffer()
+ }
+
+ advanceTimeBy(4_000)
+ assertEquals("Car Mode", switchedProfileName)
+ advanceTimeBy(2_000)
+ assertEquals("Car Mode's delay counts from when its own condition stopped", "Charging", switchedProfileName)
+ }
+
+ @Test
+ fun `a ready lower profile that stops matching has to earn its activation delay again`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10, activationDelay = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onCarModeStateChanged(true)
+ manager.onChargingStateChanged(true)
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(12_000)
+ manager.onChargingStateChanged(false)
+ advanceTimeBy(13_000)
+ manager.onChargingStateChanged(true)
+
+ advanceTimeBy(6_000)
+ assertNull("replugged 6s ago, not ready", switchedProfileName)
+ advanceTimeBy(5_000)
+ assertEquals("Charging", switchedProfileName)
+ }
+
+ @Test
+ fun `a lower profile ready before the delay ends takes over when it ends`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10, activationDelay = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.onCarModeStateChanged(true)
+ manager.onChargingStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(29_000)
+ assertEquals("Car Mode", switchedProfileName)
+
+ advanceTimeBy(2_000)
+ assertEquals("Charging", switchedProfileName)
+ assertEquals(switches + 1, switchCount)
+ }
+
+ /** The lower profile's activation delay starts when the active profile stops matching and runs alongside, not after. */
+ @Test
+ fun `a lower profile not yet ready follows the defaults on its own clock`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10, activationDelay = 45)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onCarModeStateChanged(true)
+ manager.onChargingStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(31_000)
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+
+ advanceTimeBy(13_000)
+ assertNull(switchedProfileName)
+
+ advanceTimeBy(2_000)
+ assertEquals("activation counted from 0s, not from 30s", "Charging", switchedProfileName)
+ assertEquals(switches + 2, switchCount)
+ }
+
+ @Test
+ fun `the active profile matching again cancels the handover`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10, activationDelay = 10)
+ val carMode = carModeProfile(id = 2, priority = 20)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ advanceTimeBy(5_000)
+ manager.onCarModeStateChanged(true)
+ advanceTimeBy(60_000)
+
+ assertEquals("Car Mode", switchedProfileName)
+ assertEquals(switches, switchCount)
+ }
+
+ @Test
+ fun `a zero deactivation delay hands over at once`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10)
+ val carMode = carModeProfile(id = 2, priority = 20).copy(deactivationDelaySeconds = 0)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.onChargingStateChanged(true)
+ manager.onCarModeStateChanged(true)
+ val switches = switchCount
+
+ manager.onCarModeStateChanged(false)
+ assertEquals("Charging", switchedProfileName)
+ assertEquals(switches + 1, switchCount)
+ }
+
+ @Test
+ fun `a zero deactivation delay falls back to defaults while the lower profile is not ready`() = testScope.runTest {
+ val charging = chargingProfile(id = 1, priority = 10, activationDelay = 10)
+ val carMode = carModeProfile(id = 2, priority = 20).copy(deactivationDelaySeconds = 0)
+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onCarModeStateChanged(true)
+ manager.onChargingStateChanged(true)
+
+ manager.onCarModeStateChanged(false)
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+
+ advanceTimeBy(11_000)
+ assertEquals("Charging", switchedProfileName)
+ }
+
// --- Immediate deactivation when profile disabled/deleted ---
@Test
diff --git a/fastlane/metadata/android/en-US/changelogs/51.txt b/fastlane/metadata/android/en-US/changelogs/51.txt
new file mode 100644
index 00000000..ee96b1e5
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/51.txt
@@ -0,0 +1 @@
+- A tracking profile keeps its deactivation delay when a lower-priority profile starts to match