Activity lifecycle explained in details
2011-08-09 |
|
Usually one of the biggest obstacles for the newcommers to android programming is the correct understanding of the activity's lifecycle, for example what is the difference in the event's chain when hitting "Back" button compared to activity being closed when phone is rotated. You cannot obtain this information by looking just at the activity lifecycle diagram in the API ref. In the following post I will use sample project that uses logging to demonstrate exactly what happens in the different cases. It is ment to be used as complementary tool for understanding how activities work.
Before proceeding you may want to download the sample project: Activity Lifecycle Demo. It contains simple logging of the activity and method name in each of the methods related to the lifecycle.
1. "Cold" start
Cold start is the case when the activity was a) started for the first time OR b) started after stopped with hitting "Back" button (the hardware one not <Button> that may exists in some activity's layout).
Logcat will show something like (timestamps will differ):
08-09 17:37:20.500: INFO/TEST(10107): A onCreate 08-09 17:37:20.507: INFO/TEST(10107): A onStart 08-09 17:37:20.507: INFO/TEST(10107): A onResume
Important to note here is that when onCreate(Bundle savedInstanceState)
is called savedInstanceState
is null. That is because there is no saved state because this is "cold" start (obviously).
2. Hitting "Back" button
08-09 17:50:19.050: INFO/TEST(10107): A onPause 08-09 17:50:19.433: INFO/TEST(10107): A onStop 08-09 17:50:19.433: INFO/TEST(10107): A onDestroy | isFinishing: true
Important to note here is isFinishing: true
which means that call to isFinishing()
in the onDestroy()
returns true, i.e. which happens when: (more…)