Search code examples
androidandroid-activitylifecycle

Android inter-Activity life cycle


According to Android docs, activity life cycle is as follows:

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

The question is, providing I have two activities (A and B) and that they are not killed abnormally (low memory, etc):

How is the execution order when one goes to the background and the other is restored/created?

  • ...
  • A.onPause()
  • B.onCreate()
  • A.onStop() -- B.onStart() simultaneously
  • B.onResume()
  • ...

is this guarantee to work on any specific order? in every Android version?

Regads


Solution

  • Follow the diagram you will understand what happens when one activity goes in background and other comes to foreground.

    enter image description here

    In step 2 MainActivity disappeared from the screen, but was left in memory and was not destroyed. But in the step 3 ActivityTwo was destroyed just after it disappeared from the screen. And in the step 4 in the end MainActivity was destroyed.

    This is bcos when Activity_A invokes Activity_B, Activity_B is put on the top of the Task and receives focus. Activity_A remains in the Task but is in the Stopped state (is not visible and not focused). After this, when the user clicks the Back button when Activity_B is opened, Activity_B is deleted from the task and destroyed. And Activity_A is now on the top of the Task and gains focus.

    Activities are stored in the task in the same order they were opened (and added to the Task). They are not sorted or ordered in any way inside the Task. The set of Activities in the Task is also called back stack. I will just call it - stack.

    The diagram (from the official site) demonstrates an example:

    enter image description here