Marcus
Marcus

Reputation: 725

Android: How can I save application wide instance state?

Regarding application wide state, I have read many discussions about POJO Singletons vs. subclassing Application class.

Regarding saving state, I've learned about Activity.onSaveInstanceState.

But since Application doesn't really have Lifecycle methods, how can I save state which is used from several Activities?

My first idea was to use onCreate() and onSaveInstanceState() in my main Activity, but what happens if user pauses app while being in another Activity? When the app comes back to front, only this activity, but not my main activity will be recreated, right?

Will I have to do the same onSaveInstanceState and onCreate in ALL my activites or is there another way?

Upvotes: 1

Views: 518

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006809

how can I save state which is used from several Activities?

Update your persistent store when the data changes. There is no "instance state" that is "used from several Activities", by definition.

My first idea was to use onCreate() and onSaveInstanceState() in my main Activity, but what happens if user pauses app while being in another Activity?

Eventually, your process gets terminated. "Instance state" (e.g., onSaveInstanceState()) may be supplied back to you again later, depending on circumstances. Anything you absolutely need to hold onto needs to be put into a persistent store (database, SharedPreferences, file), usually at the time that data is changed, much like how software has been written for the past 60 years.

Upvotes: 1

Related Questions