[android] Android activity life cycle - what are all these methods for?

What is the life cycle of an Android activity? Why are so many similar sounding methods (onCreate(), onStart(), onResume()) called during initialization, and so many others (onPause(), onStop(), onDestroy()) called at the end?

When are these methods called, and how should they be used properly?

This question is related to android lifecycle oncreate onresume ondestroy

The answer is


Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):

Source: developer.android.com

enter image description here

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.

onPostCreate(Bundle savedInstanceState)

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).

onPostResume()

Called when activity resume is complete (after onResume() has been called).

onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

onRestoreInstanceState(Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

My application code using all these methods:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(R.id.username);
        txtPassword=(EditText) findViewById(R.id.password);
        loginButton =  (Button)  findViewById(R.id.login);
        loginButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName",txtUserName.getText().toString());
        bundle.putString("password",txtPassword.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
       // IntentFilter
    }
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(R.id.txtView);
        txtView.setText(result);

        Intent sendIntent = new Intent();
        //sendIntent.setPackage("com.whatsapp");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Ravi","Main Start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Ravi","Main ReStart");
    }

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

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Ravi","Main Resume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Ravi","Main Stop");
    }

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

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("Ravi","Main PostResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

Login Activity:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        txtView = (TextView) findViewById(R.id.Result);
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
        intent.putExtra("result","Success");
        setResult(1,intent);
       // finish();
    }
}

output: ( Before pause)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

output: ( After resume from pause)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

Note that onPostResume() is invoked even though it's not quoted as life cycle method.


Activity has six states

  • Created
  • Started
  • Resumed
  • Paused
  • Stopped
  • Destroyed

Activity lifecycle has seven methods

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onRestart()
  • onDestroy()

activity life cycle

Situations

  • When open the app

    onCreate() --> onStart() -->  onResume()
    
  • When back button pressed and exit the app

    onPaused() -- > onStop() --> onDestory()
    
  • When home button pressed

    onPaused() --> onStop()
    
  • After pressed home button when again open app from recent task list or clicked on icon

    onRestart() --> onStart() --> onResume()
    
  • When open app another app from notification bar or open settings

    onPaused() --> onStop()
    
  • Back button pressed from another app or settings then used can see our app

    onRestart() --> onStart() --> onResume()
    
  • When any dialog open on screen

    onPause()
    
  • After dismiss the dialog or back button from dialog

    onResume()
    
  • Any phone is ringing and user in the app

    onPause() --> onResume() 
    
  • When user pressed phone's answer button

    onPause()
    
  • After call end

    onResume()
    
  • When phone screen off

    onPaused() --> onStop()
    
  • When screen is turned back on

    onRestart() --> onStart() --> onResume()
    

From the Android Developers page,

onPause():

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop():

Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.

The paused Activity gets a Resume and Stopped gets Restarted.

When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.

I hope it's clear enough.


ANDROID LIFE-CYCLE

There are seven methods that manage the life cycle of an Android application:


Answer for what are all these methods for:

Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.

  • Suppose you are using a calculator app. Three methods are called in succession to start the app.

onCreate() - - - > onStart() - - - > onResume()

  • When I am using the calculator app, suddenly a call comes the. The calculator activity goes to the background and another activity say. Dealing with the call comes to the foreground, and now two methods are called in succession.

onPause() - - - > onStop()

  • Now say I finish the conversation on the phone, the calculator activity comes to foreground from the background, so three methods are called in succession.

onRestart() - - - > onStart() - - - > onResume()

  • Finally, say I have finished all the tasks in calculator app, and I want to exit the app. Futher two methods are called in succession.

onStop() - - - > onDestroy()


There are four states an activity can possibly exist:

  • Starting State
  • Running State
  • Paused State
  • Stopped state

Starting state involves:

Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.

Running state involves:

It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.

Paused state involves:

When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.

Stopped state involves:

A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.

The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities


I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:

Android Activity Lifecycle


I run some logs as per answers above and here is the output:

Starting Activity

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Stopping The Activity

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

In my personal opinion only two are required onStart and onStop.

onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).


The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram can be interpreted as:

enter image description here


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to lifecycle

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps onNewIntent() lifecycle and registered listeners Android activity life cycle - what are all these methods for? Looking to understand the iOS UIViewController lifecycle How to retrieve the dimensions of a view?

Examples related to oncreate

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments What's onCreate(Bundle savedInstanceState) Android activity life cycle - what are all these methods for? Difference between onCreate() and onStart()? Start an Activity with a parameter

Examples related to onresume

Android - save/restore fragment state How to use onResume()? Fragment onResume() & onPause() is not called on backstack Android activity life cycle - what are all these methods for?

Examples related to ondestroy

What is Activity.finish() method doing exactly? Android activity life cycle - what are all these methods for?