Good,
When an activity is destroyed onDestroy, what happens to the classes that were instantiated in this activity, are they also destroyed or loaded into memory?
Good,
When an activity is destroyed onDestroy, what happens to the classes that were instantiated in this activity, are they also destroyed or loaded into memory?
It depends, what type of variable you declare. If it is a variable
static
, it belongs to the class and is loaded (excuse the redundancy) when the class is loaded and not when it is instantiated. On the other hand, if within the class (or the methodonCreate
in this case) you declare variables that live and die within the life cycle of yourActivity
, oneActivity
has a single instance and there cannot be two distinct instances.When
Activity
it is "Stopped" it goes to the background, since theActivity
main one is another, it is HERE where it keeps all its data as it was, all in memory. But the system is smart enough to remove it in case it needs memory space as it is not attached to the window manager.Regarding the method,
onDestroy()
it is a method that is executed BEFORE being finishedActivity
, I say it before, because for this method to be executed, someone or something must have calledfinish()
orfinishActivity()
or because the system is freeing memory that it needs.Regarding the correct thing, when one
Activity
goes to the background, it is the methodonPause()
that corresponds to handle the data that until now, youActivity
maintain, it is here where you should know what to do with that data in the event that for memory reasons they are released, important data and that only affect thisActivity
, for example the camera, animations, etc. that are only used in this instance of your activity.As a first clarification, the activity is not destroyed in the OnDestroy(). OnDestroy is a method called by the system before the activity is destroyed, this method is for you to clean what you have to clean.
Destroying an activity does not directly imply that the GC (garbage collector) is called on the activity, but if the system needs memory it will do so at any time, so you need to save all the data you don't want to lose.
El método onDestroy() en realidad es un metodo llamado por el sistema antes de que la actividad se destruya, lo cual podemos observar en el diagrama del ciclo de vida de la
Activity
.La ejecución de onDestroy() se produce por dos situaciones:
finish()
)According to your question:
I guess you want to know what happens with classes that you instantiated, well at this point when called onDestroy() it tells us that the class
Activity
is about to be destroyed and the resources released, in this case the Class instances will be destroyed.It is important to know that the Garbage Collector does not release these instances instantly.