diff --git a/piano-analytics/src/main/java/io/piano/android/analytics/SessionStorage.kt b/piano-analytics/src/main/java/io/piano/android/analytics/SessionStorage.kt index 911e83a..92c2b39 100644 --- a/piano-analytics/src/main/java/io/piano/android/analytics/SessionStorage.kt +++ b/piano-analytics/src/main/java/io/piano/android/analytics/SessionStorage.kt @@ -92,6 +92,7 @@ internal class SessionStorage( internal inline fun getCurrentTimestamp() = System.currentTimeMillis() // for mocking in tests - internal fun addLifecycleObserver(observer: DefaultLifecycleObserver) = + internal fun addLifecycleObserver(observer: DefaultLifecycleObserver) = runOnMainThread { ProcessLifecycleOwner.get().lifecycle.addObserver(observer) + } } diff --git a/piano-analytics/src/main/java/io/piano/android/analytics/Utils.kt b/piano-analytics/src/main/java/io/piano/android/analytics/Utils.kt index e098773..9463ec2 100644 --- a/piano-analytics/src/main/java/io/piano/android/analytics/Utils.kt +++ b/piano-analytics/src/main/java/io/piano/android/analytics/Utils.kt @@ -1,6 +1,8 @@ package io.piano.android.analytics import android.annotation.SuppressLint +import android.os.Handler +import android.os.Looper import timber.log.Timber internal fun String.wildcardMatches(string: String): Boolean { @@ -21,3 +23,14 @@ private fun getProperty(key: String): String? = runCatching { }.getOrNull() private const val LOG_HTTP_KEY = "debug.piano.sdk" + +internal fun runOnMainThread(action: () -> Unit) { + val mainLooper = Looper.getMainLooper() + if (mainLooper.thread == Thread.currentThread()) { + action() + } else { + Handler(mainLooper).post { + action() + } + } +}