Lifetime of a static variable in Android

前端 未结 14 2256

when I declare and initialize a variable as static in my main activity and the activity gets destroyed. Can I still access the content of the variable?

For example t

14条回答
  •  悲哀的现实
    2020-12-03 10:19

    Static variables are tied to the class itself. As long as the class is in memory, the variable will be kept.

    Classes rarely get garbage collected as they live in what is called the Permanent Generation of memory space (you can find more about how generational GC works here https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html).

    You can look at https://developer.android.com/topic/performance/memory-overview to get a better understanding of how memory is managed in Android, but unless your app is doing something very very unusual, the permanent generation is allocated all the memory it needs to hold all it's classes and will not be garbage collected.

    Orientation changes will not clear a static variable, however if that's your goal using a static variable isn't very appropriate. You can keep instance state when orientation changes by using setRetainInstance or similar (see Android: how do I prevent class variables being cleared on orientation change for an answer)

提交回复
热议问题