gpt4 book ai didi

android - 什么时候使用和不使用 android Application 类?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:05:33 24 4
gpt4 key购买 nike

我正在考虑使用 android Application类作为存储临时状态和应用程序中其他( fragment ) Activity 共享的公共(public)代码的地方。

我想获得更多关于它是否适合以下方面的反馈:

  1. 共享常量,如 ID、首选项名称等。
  2. 全局变量(即 setter/getter)反射(reflect)当前界面状态、导航、选定 fragment ,以及通常不需要保留的临时数据。
  3. 用于在触发特定条件时持久保存数据的 Hook 。
  4. 在偏好更改后更新 UI。
  5. 提供一种从应用中的任何位置访问上下文的简单方法,包括 getApplication() 不可用的代码,例如通过静态 getter,例如 MyApp.getApp()
  6. 需要全局状态变量可见性的常用方法,如果移到专用类中会变得太麻烦。

在 Activity 课上还有什么合适的/有用的/方便的?保留在其中的什么不是一个好主意,什么是最好的选择?最后,您发现 Application 最适合在您的应用中做什么?

最佳答案

Shared constants like ID's, pref key names, etc.

我通常为此创建一个名为 C 的常量文件,因为它的可读性更好。 C.SHARED_PREFSApplication.SHARED_PREFS 恕我直言更容易理解。

Global variables (i.e. setters/getters) reflecting current UI state, navigation, selected fragment, and, in general, temporary data that does not need to be persisted.

这在它所涉及的 Activity 或组件中会更好(例如,Activity 的 UI 状态可能应该存储在 icicle bundle 中,或者在 Activity 的那个实例中)。

Hooks for persisting data when certain conditions are triggered.

这应该没问题。

Updating the UI after preference changes.

同样,我觉得这在相应的组件中会更好。

Providing an easy way to access the context from anywhere in the app, including code where getApplication() is not available, e.g. via a static getter such as MyApp.getApp().

这可行,但要小心内存泄漏。当从 Activity 或 Service 或其他什么调用方法时,您通常应该将上下文作为参数传入。内存泄漏的可能性较小。

Common methods that need the visibility of the global state variables and which would become too cumbersome to move away to dedicated classes.

我觉得将精力放在专门的类上会更好,因为当您的应用在功能和规模上增长时,这将变得难以维护。

关于android - 什么时候使用和不使用 android Application 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14197800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com