Does onDestroy() or finish() actually kill the activity?

Jomia picture Jomia · May 24, 2011 · Viewed 20.4k times · Source

Actually I know i am asking about the simple and basic concept of Android. But I am a little bit confused about these finish() and onDestroy() methods. Whether this will kill the activity and free the resources associated with these activity?

I tried with a simple application which contains only one activity. I thought the concept is like When the application runs, the activity will start. and when we click on back button, it will finish. And I gave some toast message inside each life cycle methods for knowing the memory usage . And when I clicked on the back button it executed onPause(), onStop(), and onDestroy(). I thought this activity finished. But when i relaunched the application again, then it took more memory than the previous time. This happens every time when I run the app from eclipse or relaunch the application from home screen.

Why is it happening? How can i actually destroy the application / activity to free the memory?


I am including my code. I just give only one toast message inside the class. Then also memory usage is increasing.

Each time when I run the application the allocated size is increasing like : 3302744, 3442384, 3474552

 public class myActivity extends Activity
   {
         @Override
         public void onCreate(Bundle savedInstanceState)
         {
             super.onCreate(savedInstanceState);     
        Toast.makeText(getBaseContext()," allocated size  = " + Debug.getNativeHeapAllocatedSize(), 1).show();      
         }

   }

manifest:

<application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".myActivity "  
                  android:label="@string/app_name"  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity> 
 </application>

Why is the memory increasing every time?

Answer

neteinstein picture neteinstein · May 24, 2011

The finish() kills the activity and releases memory... unless you have some reference stored that is leaked... for example on methods like onRetainNonConfigurationInstance()

When you press the back button what is called is the finish() method that than calls onPause, onStop, onDestroy.