views:

2139

answers:

4

Hi

I have an activity and I call the finish() method and the activity is not cleared from memory.

After calling finish() , I see that the method onDestroy() is executed successfully (and I clear all my variables and stuff in there).

Should it be cleared from memory or its how android works? As I understand the LifeCycle of the Activity is finished.

And if it keeps the app in memory so it runs faster the 2nd time the user uses it, what kind of objects can I leave in memory to reuse? If I understand correctly, I am suppose to clear everything on onDestroy.

Thanks

Daniel

+5  A: 

Once onDestroy() gets called, your activity is doomed. Period.

That being said, the process (and hence address space) allocated to your application might still be in use by another part of your application -- another activity or service. It's also possible that your process is empty and the OS just hasn't gotten around to reclaiming it yet; it's not instant.

See the Process Lifecycle document for more information:
http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle

Regardless, if your activity is relaunched, it will have to go through the entire startup sequence again, starting with onCreate(). Do not assume that anything can implicitly be reused.

Trevor Johns
I believe this is not totally true. I don't believe the Activity is doom, because there are ways to leak memory and then the Activity will live forever.
Daniel Benedykt
Even if an activity leaks memory, when the OS kills the process the memory will be reclaimed. Just like when you terminate a process on a desktop OS.
Trevor Johns
+5  A: 

Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed. Don't worry about it :)

Romain Guy
Does this also apply for "subactivities", means if it's not the last activity open in my app? Say: if I open activity B from activity A, then B.finish(), would Android eventually keep B in memory and would I eventually also still see B in my hprof dump (in case Android didn't need to reclaim memory for elsewhere)?
Mathias Lin
A: 

According to this presentation from Google I/O 2008:

 http://sites.google.com/site/io/inside-the-android-application-framework

Finish should also cause the process to be killed, but I wrote a quick application to test this and on Android 1.5 it does not.

As Romain said (who incidentally is a UI Toolkit engineer for Android), your process will just sit there doing nothing anyways, so it is nothing to worry about.

Frank
A: 

Try using

System.exit(0);

Zahid