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

雨燕双飞 提交于 2019-12-08 12:25:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40062979/is-using-the-application-class-as-a-hack-workaround-for-configuration-changes-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!