本文介绍了是否将Application类用作可接受的配置更改的黑客解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,在一些棘手的情况下,扩展Application类并使用它保存引用和值是很有帮助的,否则通过配置更改难以在生命周期中协调。



这样做有没有真正的缺点?我不禁感到这是一个太容易的解决方案,这意味着我可能会考虑一些主要的缺点。

解决方案

我将把你的问题分解成两个子问题。

一些问题包括:


  • 内存泄漏


  • 线程安全,如果有多个线程可能触及静态值

  • 处理N个可能的值,如果您需要N个可能的值(例如,某个活动的多个实例,每个需要一个不同的值) 像保留的片段和 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类用作可接受的配置更改的黑客解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 18:17