user7021565 user7021565 - 1 year ago 82
Android Question

Is using the Application class as a hack-workaround for configuration changes acceptable?

I've found that in some tricky cases, it can be helpful to extend the Application class and use it to hold onto references and values that are otherwise hard to coordinate in the lifecycle through configuration changes.

Is there any real downside to doing this? I can't help but feel it's "too easy" a fix which means there's probably some major downside I am not considering.

Answer Source

I am going to decompose your question into two sub-questions.

Is there any real downside to [storing information in a static scope]?

Some problems include:

  • Memory leaks

  • Thread safety, if there are multiple threads that might hit the static values

  • Memory leaks

  • Handling N possible values, in cases where you might need N possible values (e.g., multiple instances of some activity, each needing a distinct value)

  • Memory leaks

  • Like retained fragments and onRetainNonConfigurationInstance(), this solution does not help with process termination and restoration for a recent task, whereas the onSaveInstanceState() Bundle helps with that too

  • Did I mention memory leaks?

Common patterns for helping to mitigate some of these things include:

  • Considering the static value to be a cache with limited size (e.g., LRUCache)

  • Using an event bus instead of your own static values

Is there any real downside to [using Application as a static scope, as opposed to just an ordinary static field somewhere]?

There is only one Application instance. Usually, it offers little value over a regular static field. And, because various libraries want you to use their "special snowflake" Application base class, the less of your own stuff you try lumping in there, the less likely it is you will run into collisions in the future.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download