问题描述
我发现,在一些棘手的情况下,扩展Application类并使用它保存引用和值是很有帮助的,否则通过配置更改难以在生命周期中协调。
这样做有没有真正的缺点?我不禁感到这是一个太容易的解决方案,这意味着我可能会考虑一些主要的缺点。
解决方案我发现,在一些棘手的情况下,扩展Application类并使用它保存引用和值是很有帮助的,否则通过配置更改难以在生命周期中协调。
这样做有没有真正的缺点?我不禁感到这是一个太容易的解决方案,这意味着我可能会考虑一些主要的缺点。
解决方案我将把你的问题分解成两个子问题。
一些问题包括:
内存泄漏
线程安全,如果有多个线程可能触及静态值
onRetainNonConfigurationInstance()
,这个解决方案不会帮助最近任务的进程终止和恢复,而 onSaveIn stanceState()
Bundle
也有帮助 泄漏?
帮助缓解这些事情的常见模式包括:
考虑到静态值是一个大小有限的缓存(例如, LRUCache
)
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
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.
这篇关于是否将Application类用作可接受的配置更改的黑客解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!