Skip to content

Commit

Permalink
prevent ANRs on background app event
Browse files Browse the repository at this point in the history
Move calls to methods that do disk I/O from the main thread to a new
background thread.

There are reports where this can cause a significant amount of time on
main thread. Any disk I/O is a risk on the main thread and should not be
done as there is no upper bond of how long it can take. ANRs trigger
after 5 seconds of the main thread being busy.

The stacktrace of reported ANRs confirm that appStopped then calls
getSessionInfluences which can result in waiting on disk I/O.
We have also seen stacktraces with scheduling a AndroidX worker so
that was moved into this background thread as well. I isn't known if it
does any disk I/O but it was significant enough to show up in some ANRs
  • Loading branch information
jkasten2 committed May 10, 2023
1 parent 0a313f2 commit 56dd55b
Showing 1 changed file with 8 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,14 @@ private void handleLostFocus() {
if (focusHandler == null || focusHandler.hasBackgrounded() && !focusHandler.hasCompleted())
return;

OneSignal.getFocusTimeController().appStopped();
focusHandler.startOnLostFocusWorker(FOCUS_LOST_WORKER_TAG, SYNC_AFTER_BG_DELAY_MS, OneSignal.appContext);
new Thread() {
public void run() {
// Run on it's own thread since both these calls do disk I/O
// which could contribute a significant amount to ANRs.
OneSignal.getFocusTimeController().appStopped();
focusHandler.startOnLostFocusWorker(FOCUS_LOST_WORKER_TAG, SYNC_AFTER_BG_DELAY_MS, OneSignal.appContext);
}
}.start();
}

private void handleFocus() {
Expand Down

0 comments on commit 56dd55b

Please sign in to comment.