From b0f4fea58d808129c0bd46a7624f8a1e541bc6c6 Mon Sep 17 00:00:00 2001 From: Justin Fiedler Date: Fri, 21 Jul 2023 12:47:26 -0700 Subject: [PATCH] fix: try to correctly handle session change for race condition (#382) * fix: try to correctly handle session change for race condition * fix: set isEnteringForeground to false on exit foreground --- .../java/com/amplitude/api/AmplitudeClient.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/amplitude/api/AmplitudeClient.java b/src/main/java/com/amplitude/api/AmplitudeClient.java index 40b10ea8..8175c333 100644 --- a/src/main/java/com/amplitude/api/AmplitudeClient.java +++ b/src/main/java/com/amplitude/api/AmplitudeClient.java @@ -181,6 +181,7 @@ public class AmplitudeClient { private boolean usingForegroundTracking = false; private boolean trackingSessionEvents = false; private boolean inForeground = false; + private boolean isEnteringForeground = false; private boolean flushEventsOnClose = true; private String libraryName = Constants.LIBRARY; private String libraryVersion = Constants.VERSION; @@ -1221,7 +1222,8 @@ protected long logEvent(String eventType, JSONObject eventProperties, JSONObject if (!loggingSessionEvent && !outOfSession) { // default case + corner case when async logEvent between onPause and onResume - if (!inForeground){ + if (!inForeground || isEnteringForeground){ + isEnteringForeground = false; startNewSessionIfNeeded(timestamp); } else { refreshSessionTime(timestamp); @@ -1573,6 +1575,7 @@ private void sendSessionEvent(final String sessionEvent) { * @param timestamp the timestamp */ void onExitForeground(final long timestamp) { + isEnteringForeground = false; inForeground = false; runOnLogThread(new Runnable() { @Override @@ -1602,6 +1605,7 @@ public void run() { * @param timestamp the timestamp */ void onEnterForeground(final long timestamp) { + isEnteringForeground = true; inForeground = true; runOnLogThread(new Runnable() { @Override @@ -1617,7 +1621,13 @@ public void onFinished() { } }, serverZone); } - startNewSessionIfNeeded(timestamp); + // This should be true, unless somehow an event was tracked + // between here and the beginning of this method + // in that case the session is started in logEvent() + if (isEnteringForeground) { + startNewSessionIfNeeded(timestamp); + } + isEnteringForeground = false; } }); }