Home » Android » android – Why does singleton class survive Activity exit?

android – Why does singleton class survive Activity exit?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a Singleton class which I use with the one of the activities of my application.

When I exit the activity – which brings me back to the menu activity – and then reopen the activity I find that when I try to access the singleton it is still the same.
Surely it should have been destroyed with the Activity?

I saw the question here: living singleton, when activity end
but could not quite follow what they mean.

When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use? If so, then that would explain it.

How to&Answers:

Surely it should have been destroyed with the Activity?

No.

When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use?

The activity is not. The process is. Singletons are part of the virtual machine and will live as long as the process does. Exiting the last activity does not immediately terminate the process, so the singleton lives on… at least for a while.

Android will eventually terminate that process to free up memory for other apps. How quickly it will do that depends on what the user is doing, what apps are installed, phase of the moon, etc.