Skip to content

Commit

Permalink
fix androidx lifecycle causes analytics init in background crash (#824)
Browse files Browse the repository at this point in the history
* fix androidx lifecycle causes analytics init in background crash

* fix typo
  • Loading branch information
wenxi-zeng authored Mar 13, 2023
1 parent 64dc7c7 commit 8c65fc0
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions analytics/src/main/java/com/segment/analytics/Analytics.java
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,12 @@ public void run() {

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

Expand Down Expand Up @@ -799,6 +804,15 @@ public void run() {
});
}

private void run(Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
}
else {
HANDLER.post(runnable);
}
}

/**
* Asynchronously flushes all messages in the queue to the server, and tells bundled
* integrations to do the same.
Expand Down Expand Up @@ -1000,7 +1014,7 @@ public void shutdown() {
application.unregisterActivityLifecycleCallbacks(activityLifecycleCallback);
if (useNewLifecycleMethods) {
// only unregister if feature is enabled
lifecycle.removeObserver(activityLifecycleCallback);
run(() ->lifecycle.removeObserver(activityLifecycleCallback));
}
// Only supplied by us for testing, so it's ok to shut it down. If we were to make this
// public,
Expand Down

0 comments on commit 8c65fc0

Please sign in to comment.