Skip to content

Commit 462dea2

Browse files
fix(app-start): Fix detection of foreground app start (#5880)
* fix(app-start): Fix detection of foreground app start * Update sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java Co-authored-by: arb <adam.brown@sentry.io> * Update Changelog --------- Co-authored-by: arb <adam.brown@sentry.io>
1 parent 934244e commit 462dea2

3 files changed

Lines changed: 54 additions & 36 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
### Fixes
66

7+
- Prevent inflated cold app start when the OS spawns the process in the background (e.g. FCM push) on API 35+ ([#5841](https://github.com/getsentry/sentry-java/pull/5841), [#5880](https://github.com/getsentry/sentry-java/pull/5880))
78
- Preserve single-sample ANR profile chunks so profiles remain available on ANR events ([#5872](https://github.com/getsentry/sentry-java/pull/5872))
8-
- Prevent inflated cold app start when the OS spawns the process in the background (e.g. FCM push) on API 35+ ([#5841](https://github.com/getsentry/sentry-java/pull/5841))
99
- Avoid a CPU busy-loop when recording discarded log or metric envelopes under rate limiting ([#5835](https://github.com/getsentry/sentry-java/pull/5835))
1010
- `ClientReportRecorder` now reads the item count from the envelope item header instead of deserializing the payload, which under sustained rate limiting could pin CPU cores while repeatedly throwing exceptions
1111
- Report tasks handed to a no-op `ISentryExecutorService` as cancelled ([#5874](https://github.com/getsentry/sentry-java/pull/5874))

‎sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java‎

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
import io.sentry.android.core.internal.util.FirstDrawDoneListener;
3131
import io.sentry.protocol.SentryId;
3232
import io.sentry.util.AutoClosableReentrantLock;
33-
import io.sentry.util.LazyEvaluator;
3433
import java.util.ArrayList;
3534
import java.util.Collections;
3635
import java.util.HashMap;
@@ -70,14 +69,7 @@ public enum AppStartType {
7069
new AutoClosableReentrantLock();
7170

7271
private @NotNull AppStartType appStartType = AppStartType.UNKNOWN;
73-
private final LazyEvaluator<Boolean> appLaunchedInForeground =
74-
new LazyEvaluator<>(
75-
new LazyEvaluator.Evaluator<Boolean>() {
76-
@Override
77-
public @NotNull Boolean evaluate() {
78-
return ContextUtils.isForegroundImportance();
79-
}
80-
});
72+
private @Nullable volatile Boolean appLaunchedInForeground;
8173
private volatile long firstIdle = -1;
8274

8375
private final @NotNull TimeSpan appStartSpan;
@@ -239,12 +231,12 @@ public void setAppStartType(final @NotNull AppStartType appStartType) {
239231
}
240232

241233
public boolean isAppLaunchedInForeground() {
242-
return appLaunchedInForeground.getValue();
234+
return Boolean.TRUE.equals(appLaunchedInForeground);
243235
}
244236

245237
@VisibleForTesting
246238
public void setAppLaunchedInForeground(final boolean appLaunchedInForeground) {
247-
this.appLaunchedInForeground.setValue(appLaunchedInForeground);
239+
this.appLaunchedInForeground = appLaunchedInForeground;
248240
}
249241

250242
public void setHeadlessAppStartListener(final @Nullable HeadlessAppStartListener listener) {
@@ -318,8 +310,7 @@ public void onAppStartSpansSent() {
318310
}
319311

320312
public boolean shouldSendStartMeasurements(final boolean ignoreForegroundCheck) {
321-
return shouldSendStartMeasurements
322-
&& (ignoreForegroundCheck || appLaunchedInForeground.getValue());
313+
return shouldSendStartMeasurements && (ignoreForegroundCheck || isAppLaunchedInForeground());
323314
}
324315

325316
public boolean shouldSendStartMeasurements() {
@@ -349,7 +340,7 @@ public long getClassLoadedUptimeMs() {
349340
final @NotNull SentryAndroidOptions options) {
350341
// If the app start type was never determined or app wasn't launched in foreground,
351342
// the app start is considered invalid
352-
if (appStartType != AppStartType.UNKNOWN && appLaunchedInForeground.getValue()) {
343+
if (appStartType != AppStartType.UNKNOWN && isAppLaunchedInForeground()) {
353344
if (options.isEnablePerformanceV2()) {
354345
// Only started when sdk version is >= N
355346
final @NotNull TimeSpan appStartSpan = getAppStartTimeSpan();
@@ -412,7 +403,7 @@ public void clear() {
412403
}
413404
appStartContinuousProfiler = null;
414405
appStartSamplingDecision = null;
415-
appLaunchedInForeground.resetValue();
406+
appLaunchedInForeground = null;
416407
isCallbackRegistered = false;
417408
shouldSendStartMeasurements = true;
418409
firstDrawDone.set(false);
@@ -510,7 +501,7 @@ public void registerLifecycleCallbacks(final @NotNull Application application) {
510501
return;
511502
}
512503
isCallbackRegistered = true;
513-
appLaunchedInForeground.resetValue();
504+
appLaunchedInForeground = null;
514505
application.registerActivityLifecycleCallbacks(instance);
515506

516507
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
@@ -529,7 +520,7 @@ public void registerLifecycleCallbacks(final @NotNull Application application) {
529520
} else {
530521
appStartType = AppStartType.WARM;
531522
}
532-
appLaunchedInForeground.setValue(isForegroundStartReason(info.getReason()));
523+
appLaunchedInForeground = isForegroundStartReason(info.getReason());
533524
}
534525
}
535526
} catch (RuntimeException ignored) {
@@ -543,6 +534,10 @@ public void registerLifecycleCallbacks(final @NotNull Application application) {
543534
}
544535
}
545536
}
537+
// Fallback, if no matching ApplicationStartInfo is available
538+
if (appLaunchedInForeground == null) {
539+
appLaunchedInForeground = ContextUtils.isForegroundImportance();
540+
}
546541

547542
if (appStartType == AppStartType.UNKNOWN || headlessAppStartListener != null) {
548543
scheduleHeadlessAppStartCheckOnMain();
@@ -591,7 +586,7 @@ private void handleHeadlessAppStartIfNeededOnMain() {
591586
return;
592587
}
593588

594-
appLaunchedInForeground.setValue(false);
589+
appLaunchedInForeground = false;
595590

596591
// Headless starts have no Activity signal for the pre-API 35 warm/cold heuristic.
597592
// If ApplicationStartInfo did not resolve the type, classify the process start as cold.
@@ -677,7 +672,7 @@ public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle saved
677672
// An active extension explicitly keeps the launch alive: resetting the span here would make
678673
// the extended vital measure from the activity while the eager app.start transaction stays
679674
// anchored at process start.
680-
if ((!appLaunchedInForeground.getValue()
675+
if ((!isAppLaunchedInForeground()
681676
|| durationSinceAppStartMillis > TimeUnit.MINUTES.toMillis(1))
682677
&& !appStartExtension.isActive()) {
683678
appStartType = AppStartType.WARM;
@@ -698,7 +693,7 @@ public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle saved
698693
}
699694
}
700695
}
701-
appLaunchedInForeground.setValue(true);
696+
appLaunchedInForeground = true;
702697
}
703698

704699
@Override
@@ -744,7 +739,7 @@ public void onActivityDestroyed(@NonNull Activity activity) {
744739
// as the next onActivityCreated will treat it as a new warm app start
745740
if (remainingActivities == 0 && !activity.isChangingConfigurations()) {
746741
appStartType = AppStartType.WARM;
747-
appLaunchedInForeground.setValue(true);
742+
appLaunchedInForeground = true;
748743
shouldSendStartMeasurements = true;
749744
firstDrawDone.set(false);
750745
}

‎sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTest.kt‎

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -241,15 +241,16 @@ class AppStartMetricsTest {
241241
}
242242

243243
@Test
244-
fun `headless app start fires HeadlessAppStartListener`() = headlessProcess {
245-
val listenerCalls = AtomicInteger()
244+
fun `headless app start fires HeadlessAppStartListener`() =
245+
withProcessImportance(false) {
246+
val listenerCalls = AtomicInteger()
246247

247-
AppStartMetrics.getInstance().setHeadlessAppStartListener { listenerCalls.incrementAndGet() }
248-
AppStartMetrics.getInstance().registerLifecycleCallbacks(mock<Application>())
249-
waitForMainLooperIdle()
248+
AppStartMetrics.getInstance().setHeadlessAppStartListener { listenerCalls.incrementAndGet() }
249+
AppStartMetrics.getInstance().registerLifecycleCallbacks(mock<Application>())
250+
waitForMainLooperIdle()
250251

251-
assertEquals(1, listenerCalls.get())
252-
}
252+
assertEquals(1, listenerCalls.get())
253+
}
253254

254255
@Test
255256
fun `foreground process does not fire HeadlessAppStartListener`() {
@@ -295,7 +296,7 @@ class AppStartMetricsTest {
295296

296297
@Test
297298
fun `resolveHeadlessAppStartEndTime uses applicationOnCreate stop when Gradle plugin instrumented`() =
298-
headlessProcess {
299+
withProcessImportance(false) {
299300
val metrics = AppStartMetrics.getInstance()
300301
metrics.appStartTimeSpan.setStartedAt(100)
301302
metrics.setHeadlessAppStartListener {}
@@ -312,7 +313,7 @@ class AppStartMetricsTest {
312313

313314
@Test
314315
fun `resolveHeadlessAppStartEndTime falls back to CLASS_LOADED_UPTIME_MS when no plugin and no ApplicationStartInfo`() =
315-
headlessProcess {
316+
withProcessImportance(false) {
316317
val metrics = AppStartMetrics.getInstance()
317318
metrics.setClassLoadedUptimeMs(200)
318319
metrics.appStartTimeSpan.setStartedAt(100)
@@ -371,12 +372,18 @@ class AppStartMetricsTest {
371372
Shadows.shadowOf(Looper.getMainLooper()).idle()
372373
}
373374

374-
// Simulates a real headless start (broadcast/service), i.e. a non-foreground-importance process.
375-
// The Robolectric default importance in this test class is IMPORTANCE_FOREGROUND, so headless
376-
// scenarios must opt into a background importance explicitly.
377-
private fun <T> headlessProcess(block: () -> T): T =
375+
/**
376+
* Mocks the process importance to simulate a user initiated start (e.g. launcher) or a real
377+
* headless start (broadcast/service), i.e. a non-foreground-importance process.
378+
*
379+
* The Robolectric default importance in this test class is IMPORTANCE_FOREGROUND, so any headless
380+
* scenarios must opt into a background importance explicitly.
381+
*/
382+
private fun <T> withProcessImportance(isForeground: Boolean, block: () -> T): T =
378383
mockStatic(ContextUtils::class.java).use { contextUtils ->
379-
contextUtils.`when`<Boolean> { ContextUtils.isForegroundImportance() }.thenReturn(false)
384+
contextUtils
385+
.`when`<Boolean> { ContextUtils.isForegroundImportance() }
386+
.thenReturn(isForeground)
380387
block()
381388
}
382389

@@ -1123,4 +1130,20 @@ class AppStartMetricsTest {
11231130
assertEquals(now, metrics.appStartTimeSpan.startUptimeMs)
11241131
metrics.appStartExtension.setExtendAppStartListener(null)
11251132
}
1133+
1134+
@Test
1135+
fun `broadcast starts are not considered a foreground start`() =
1136+
withProcessImportance(false) {
1137+
val metrics = AppStartMetrics.getInstance()
1138+
metrics.registerLifecycleCallbacks(mock<Application>())
1139+
assertFalse(metrics.isAppLaunchedInForeground)
1140+
}
1141+
1142+
@Test
1143+
fun `typical app starts are considered a foreground start`() =
1144+
withProcessImportance(true) {
1145+
val metrics = AppStartMetrics.getInstance()
1146+
metrics.registerLifecycleCallbacks(mock<Application>())
1147+
assertTrue(metrics.isAppLaunchedInForeground)
1148+
}
11261149
}

0 commit comments

Comments
 (0)