本文介绍了当使用和不使用Android应用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Android 应用程序类作为存储临时状态,共同的地方考虑code。通过在App其他(片段)活动共享。

我想获得更多的反馈,无论是好地方:

  1. 共享一样的ID,preF键名称等常量。
  2. 在全局变量(如制定者/吸气),反映当前的UI状态,导航,选择的片段,并且在不需要被持久化一般情况下,临时数据。
  3. 挂钩持久化数据时,一定条件下被触发。
  4. 在更新后的preference改变用户界面。
  5. 提供了一种简单的方法来从任何地方访问上下文中的应用程序,其中包括code其中 getApplication()不可用,如:通过静态吸气,如 MyApp.getApp()
  6. 需要全局状态变量的知名度和这将成为太麻烦了搬开专用类
  7. 在常用的方法。

还有什么是适当/实用/方便有在活动课?什么不会是一个好主意,以保持它,这将是最好的选择吗?最后,你有什么发现应用程序将最好的你的应用程序使用?

解决方案

我一般创建一个名为℃,这是一个常数文件,其更好的可读性。 C.SHARED_ preFS 更容易理解 Application.SHARED_ preFS 恕我直言。

这将是在活动或组件,它涉及(例如,活动的UI状态也许应该存储在冰柱包,或活动的该实例内)。最好

这应该是不错。

此外,我觉得这将是在各自的成分更好。

这会工作,但要注意的内存泄漏。调用从活动或服务或任何方法时,您通常应该通过上下文作为参数。机会较少的内存泄漏。

我觉得这将是更明智的专用类的工作,因为当你的应用程序生长在功能和规模,这将变得难以维护。

I am considering using the android Application class as a place to store temporary state and common code shared by other (fragment) activities in the app.

I would like to get more feedback as to whether it is a good place for:

  1. Shared constants like ID's, pref key names, etc.
  2. 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.
  3. Hooks for persisting data when certain conditions are triggered.
  4. Updating the UI after preference changes.
  5. 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().
  6. Common methods that need the visibility of the global state variables and which would become too cumbersome to move away to dedicated classes.

What else would be appropriate/useful/handy to have in the activity class? What would not be a good idea to keep in it and what would be the best alternatives? And finally, what you have found Application to be best used for in your apps?

解决方案

I generally create a constants file called C for this, as its better for readability. C.SHARED_PREFS is easier to understand that Application.SHARED_PREFS IMHO.

This would be better off in the Activity or component which it concerns (for example, the UI state of an Activity should probably stored in the icicle bundle, or within that instance of the Activity).

This should be fine.

Again, I feel this would be better off in the respective component.

This would work, but be careful of memory leaks. You should generally pass the context in as a parameter when calling the method from an Activity or Service or whatever. Less chances of a memory leak.

I feel it would be better to make the effort of dedicated classes, as when your app grows in features and size, this will become difficult to maintain.

这篇关于当使用和不使用Android应用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 14:18