Question

I am trying to learn more about activity lifecycle. I could successfully log all the lifecycle events. Now, I am trying to know how to destroy an activity when I click a button say "Destroy". My code is below :

package com.mavenmaverick.lifecycle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

  String LOG_TAG = "EVENT";

    @Override
    public void onCreate(Bundle savedInstanceState) {
      Log.d(LOG_TAG, "onCreate()");
      super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart()
    {
      Log.d(LOG_TAG, "onStart()");
      super.onStart();
    }

    @Override
    public void onStop()
    {
      Log.d(LOG_TAG, "onStop()");
      super.onStop();
    }

    @Override
    protected void onDestroy() {
      Log.d(LOG_TAG, "onDestroy()");
      super.onDestroy();
    }

    @Override
    protected void onPause() {
      Log.d(LOG_TAG, "onPause()");
      super.onPause();
    }

    @Override
    protected void onResume() {
      Log.d(LOG_TAG, "onResume()");
      super.onResume();
    }
}
Was it helpful?

Solution

Call finish() finish() will trigger onDestroy()

First, this answer assumes that you are referring to Android's Activity class and its finish() method and onDestroy() lifecycle method.

Second, it depends upon your definition of "sure":

Your process could be terminated in between finish() and onDestroy(), for reasons independent of whatever is triggering the call to finish()

  • A device manufacturer or ROM modder could introduce some screwy change that would break the connection between finish() and onDestroy()

  • The battery could go dead in between finish() and onDestroy()Etc.

  • Third, finish() does not call onDestroy(). You can tell that by reading the source code. finish() usually triggers a call to onDestroy().

Generally speaking, finish() will eventually result in onDestroy() being called.

Here's the Android: Will finish() ALWAYS call onDestroy()? from which the answer is referred.

Yes, finish() removes the activity from the activity stack.

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.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

Referred the above from what exactly Activity.finish() method is doing?

Here go through this http://developer.android.com/training/basics/activity-lifecycle/index.html

OTHER TIPS

Just call finish() in onClickListener of button

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top