androidandroid-activityandroid-lifecycle

Application lifecycle when app is killed in the background


Some background on a problem that I have been encountering: in my app I have a singleton object that I use regularly to access things like id and token for network calls. Sometimes when the app is killed in the background, this singleton loses its state. However, when the app is opened again and starts up in some Activity past the launcher Activity, the singleton is null.

I am in the process of refactoring this, but have been agonizing over how to ensure that the singleton will always be present even in app restart, but I'm not sure what Android does when the app restarts from being backgrounded.

I went through source code in some of the libraries we use in the app (Facebook, Intercom) to see how they manage their singletons and why their static variables seemed to just always be present, and came upon a theory.

So on a normal app cold start, the app behaves like this:

Application.onCreate() -> Launcher.onCreate() -> Activity A -> Activity B

Say the user was in Activity B and backgrounds the app. After using some other apps, they come back to my app but it has been killed at some point in between. The lifecycle then becomes this:

Application.onCreate() -> Activity B

I think the problem is that I initialize the singleton in the launcher Activity, and as a result, when B tries to get a value from the singleton, it comes up null. If I initialize the singleton in Application.onCreate(), it will always be initialized when the app is pulled up again. Is this correct?

TL;DR An application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the Activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().


Solution

  • A application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().

    Correct.

    I think the problem is that I initialize the singleton in the LauncherActivity, and as a result, when B tries to get a value from the singleton, it comes up null. If I initialize the Singleton in Application.onCreate(), it will always be initialized when the app is pulled up again. Is this correct?

    In your case the problem is really in that. However, if by "it comes up null" you mean the singleton instance is null then it is not how a singleton is supposed to work. No matter where you call singleton's methods from, its instance should not be null.