Skip to content

Commit c32db12

Browse files
authored
Update amplitude destination to retain session ID (#6)
* Update amplitude destination to retain session ID According to amplitude docs, a session should include all events within 5 minutes of each other. This changes the previous implementation's behavior of creating a new session ID ever 5 minutes. * Fixing type comparison error * Adding an optional configuration for amplitude session timeout, tested manually on android emulator
1 parent 28a69df commit c32db12

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

lib/src/main/java/com/segment/analytics/kotlin/destinations/amplitude/AmplitudeSession.kt

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import java.util.*
1010
import kotlin.concurrent.schedule
1111

1212
// A Destination plugin that adds session tracking to Amplitude cloud mode.
13-
class AmplitudeSession : Plugin, VersionedPlugin {
13+
class AmplitudeSession (sessionTimeoutMs : Long = 300000) : Plugin, VersionedPlugin {
1414

1515
override val type: Plugin.Type = Plugin.Type.Enrichment
1616
override lateinit var analytics: Analytics
@@ -19,7 +19,7 @@ class AmplitudeSession : Plugin, VersionedPlugin {
1919
private var active = false
2020

2121
private var timer: TimerTask? = null
22-
private val fireTime: Long = 300000
22+
private val fireTime: Long = sessionTimeoutMs
2323

2424
override fun update(settings: Settings, type: Plugin.UpdateType) {
2525
active = settings.hasIntegrationSettings(key)
@@ -33,6 +33,7 @@ class AmplitudeSession : Plugin, VersionedPlugin {
3333
message = "Running ${payload.type} payload through AmplitudeSession",
3434
kind = LogFilterKind.DEBUG
3535
)
36+
refreshSessionID()
3637
returnPayload =
3738
payload.putIntegrations(key, mapOf("session_id" to sessionID)) as T?
3839
}
@@ -96,21 +97,25 @@ class AmplitudeSession : Plugin, VersionedPlugin {
9697
}
9798

9899
private fun onBackground() {
99-
stopTimer()
100100
}
101101

102102
private fun onForeground() {
103-
startTimer()
103+
refreshSessionID()
104104
}
105105

106+
private fun refreshSessionID() {
107+
if (sessionID == -1L) {
108+
// get a new session ID if we've been inactive for more than 5 min
109+
sessionID = Calendar.getInstance().timeInMillis
110+
}
111+
startTimer()
112+
}
113+
106114
private fun startTimer() {
107-
108-
// Set the session id
109-
sessionID = Calendar.getInstance().timeInMillis
110-
115+
timer?.cancel()
111116
timer = Timer().schedule(fireTime) {
117+
// invalidate the session ID at the end of the timer
112118
stopTimer()
113-
startTimer()
114119
}
115120
}
116121

@@ -122,4 +127,4 @@ class AmplitudeSession : Plugin, VersionedPlugin {
122127
override fun version(): String {
123128
return BuildConfig.VERSION_NAME
124129
}
125-
}
130+
}

0 commit comments

Comments
 (0)