Skip to content

Commit 8c65fc0

Browse files
authored
fix androidx lifecycle causes analytics init in background crash (#824)
* fix androidx lifecycle causes analytics init in background crash * fix typo
1 parent 64dc7c7 commit 8c65fc0

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

analytics/src/main/java/com/segment/analytics/Analytics.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,12 @@ public void run() {
352352

353353
application.registerActivityLifecycleCallbacks(activityLifecycleCallback);
354354
if (useNewLifecycleMethods) {
355-
lifecycle.addObserver(activityLifecycleCallback);
355+
// NOTE: addObserver is required to run on UI thread,
356+
// though we made it compatible to run from background thread,
357+
// there is a chance that lifecycle events get lost if init
358+
// analytics from background (i.e. analytics is init, but
359+
// lifecycle hook is yet to be registered.
360+
run(() -> lifecycle.addObserver(activityLifecycleCallback));
356361
}
357362
}
358363

@@ -799,6 +804,15 @@ public void run() {
799804
});
800805
}
801806

807+
private void run(Runnable runnable) {
808+
if (Looper.myLooper() == Looper.getMainLooper()) {
809+
runnable.run();
810+
}
811+
else {
812+
HANDLER.post(runnable);
813+
}
814+
}
815+
802816
/**
803817
* Asynchronously flushes all messages in the queue to the server, and tells bundled
804818
* integrations to do the same.
@@ -1000,7 +1014,7 @@ public void shutdown() {
10001014
application.unregisterActivityLifecycleCallbacks(activityLifecycleCallback);
10011015
if (useNewLifecycleMethods) {
10021016
// only unregister if feature is enabled
1003-
lifecycle.removeObserver(activityLifecycleCallback);
1017+
run(() ->lifecycle.removeObserver(activityLifecycleCallback));
10041018
}
10051019
// Only supplied by us for testing, so it's ok to shut it down. If we were to make this
10061020
// public,

0 commit comments

Comments
 (0)