@@ -357,6 +357,42 @@ public void testGaugeCounterStartsAJobToConsumeTheGeneratedMetrics() {
357357 assertThat (recordedGaugeMetric .getSessionId ()).isEqualTo (testSessionId (1 ));
358358 }
359359
360+ @ Test
361+ public void testUpdateAppStateFlushesMetricsInTheCurrentAppState () {
362+ PerfSession fakeSession = createTestSession (1 );
363+ fakeSession .setGaugeAndEventCollectionEnabled (true );
364+ testGaugeManager .setApplicationProcessState (ApplicationProcessState .FOREGROUND );
365+ testGaugeManager .startCollectingGauges (fakeSession );
366+ GaugeCounter .INSTANCE .setGaugeManager (testGaugeManager );
367+
368+ // There's no job to log the gauges.
369+ assertThat (fakeScheduledExecutorService .isEmpty ()).isTrue ();
370+
371+ // Generate metrics that don't exceed the GaugeCounter.MAX_COUNT.
372+ generateMetricsAndIncrementCounter (10 );
373+
374+ // There's still no job to log the gauges.
375+ assertThat (fakeScheduledExecutorService .isEmpty ()).isTrue ();
376+
377+ testGaugeManager .onUpdateAppState (ApplicationProcessState .BACKGROUND );
378+
379+ assertThat (fakeScheduledExecutorService .isEmpty ()).isFalse ();
380+ assertThat (fakeScheduledExecutorService .getDelayToNextTask (TimeUnit .MILLISECONDS ))
381+ .isEqualTo (TIME_TO_WAIT_BEFORE_FLUSHING_GAUGES_QUEUE_MS );
382+
383+ fakeScheduledExecutorService .simulateSleepExecutingAtMostOneTask ();
384+ GaugeMetric recordedGaugeMetric =
385+ getLastRecordedGaugeMetric (ApplicationProcessState .FOREGROUND , 1 );
386+
387+ // It flushes all metrics in the ConcurrentLinkedQueues.
388+ int recordedGaugeMetricsCount =
389+ recordedGaugeMetric .getAndroidMemoryReadingsCount ()
390+ + recordedGaugeMetric .getCpuMetricReadingsCount ();
391+ assertThat (recordedGaugeMetricsCount ).isEqualTo (10 );
392+
393+ assertThat (recordedGaugeMetric .getSessionId ()).isEqualTo (testSessionId (1 ));
394+ }
395+
360396 @ Test
361397 public void testStopCollectingGaugesStopsCollectingAllGaugeMetrics () {
362398 PerfSession fakeSession = createTestSession (1 );
0 commit comments