Static member views in activity - Android

后端 未结 4 671
栀梦
栀梦 2020-12-20 05:49

In each of the activities in my application, all the views (grids/lists/buttons... lots of them) are declared as static members of the activity. Is this good practice or is

4条回答
  •  猫巷女王i
    2020-12-20 05:51

    http://developer.android.com/training/articles/perf-tips.html. Check the documentation to understand when to use static variables.

    I agree with Boardy's comment. Why do you need your ui elements to be static.

    Using static variables is not recommended. Static variables are stored in a PermGen section of the heap. Even if the class finishes it works the static variables stays in the heap. The garbage collector does mark and sweep. If you have a static variables in the 1st activity which is referenced in the 2nd activity, the link stays long. You might get memory leaks if your using more static variables. Also reduce use of unnecessary objects.

    Static variables are referenced by Class objects which are referenced by ClassLoaders -so unless either the ClassLoader drops the Class somehow or the ClassLoader itself becomes eligible for garbage collection the static variables won't be garbage collected. So if you are using static variables referenced in many class those classes and the one in which static variables are declared cannot be garbage collected unless those classes are available for garbage collection. So this leads to heap memory expanding leading to memory leaks.

    In this video the guy talks about why static variables should not be used and how to avoid memory leaks.http://www.youtube.com/watch?v=_CruQY55HOk. The guy talks about using MAT Analyzer to check for memory leaks.

    Also have a look at this link. http://developer.android.com/guide/faq/framework.html.Have a look at the details under the heading *How do I pass data between Activities/Services within a single application?.

提交回复
热议问题