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; } }); }