How long do classes with static methods live on Android?

This is the next question to one of my previous questions .

I have a LoadActivity that loads some graphics needed by all the actions and stores it in a static class. I try not to load LoadingActivity again when I press HOME and resume the application, since it takes up a lot of memory and ends after several times when the graphics are already loaded, so there is no need to run LoadActivity again. My question is: how long does a static class live? Can I rely on its availability after resuming the application, or maybe it will be here, since Android is killing it due to memory problems, or is it always here while vm is running (this means that as long as the phone is working)?

+5
source share
1 answer

As Simon points out, a โ€œstatic classโ€ means different things in different languages, and Java has nothing like static classes in some other languages, but I donโ€™t think what you are talking about. It seems you are asking if objects referenced by strong static links can collect garbage. If so, the answer is no.

A class is represented by an object of the Class class, accessible through its ClassLoader . Thus, everything that the Class refers to will be available until it reaches ClassLoader , which is the case with the system class loader, as long as Java / Dalvik VM exists. But this is not as long as the phone works, since an independent virtual machine is created for each application. The entire process and the virtual machine in which the application is running can be killed whenever the application is in the background. When you return to the application, its classes will be reloaded.

If static fields are really the best choice, unlike the ContentProvider or foregound Service , then every time your application resumes, you will need to check if the static links have been initialized and reinitialized if they are null.

+6
source

Source: https://habr.com/ru/post/1202616/


All Articles