Tuesday, 19 May 2015

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?
Why this question has been upvoted so many times? Why it has not been closed? –  Alex May 26 '13 at 19:29
Why close a question with a lot of upvotes? Stackoverflow has a bad habit of that. –  Richard Jun 11 '14 at 20:16
This is a wiki-style question and I feel it should be allowed on the site. –  Mateen Ulhaq Nov 29 '14 at 22:00
How to go directly from onResume() to onPause() in an activity? –  The Hunter Apr 9 at 16:57

6 Answers

up vote345down voteaccepted
See it in Activity Lifecycle (at Android Developers).
Enter image description here
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
When the Activity first time loads the events are called as below:
When you click on Phone button the Activity goes to the background and the below events are called:
Exit the phone dialer and the below events will be called:
When you click the back button OR try to finish() the activity the events are called as below:

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:
These states can be broken into three main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.
Sample activity to understand the life cycle*
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
       Log.d(tag, "In the onCreate() event");
    public void onStart()
       Log.d(tag, "In the onStart() event");
    public void onRestart()
       Log.d(tag, "In the onRestart() event");
    public void onResume()
       Log.d(tag, "In the onResume() event");
    public void onPause()
       Log.d(tag, "In the onPause() event");
    public void onStop()
       Log.d(tag, "In the onStop() event");
    public void onDestroy()
       Log.d(tag, "In the onDestroy() event");
@Taqub Ahmad Thank you for the explanation.Now i got it :) –  Nav Dec 15 '11 at 15:05
So if I understood it correctly onStop() is always called after onPause() ? –  Titouan de Bailleul Oct 31 '12 at 16:19
NOT always, "onStop(): Called when you are no longer visible to the user" –  Yaqub Ahmad Nov 26 '12 at 8:22
Is there anything by any chance that gets called before onCreate? –  Aaron Russell Sep 23 '13 at 3:31
Yes there is - the default constructor (that's the one with no parameters). But it has only very limited use for very basic initialization purposes. Usually you should not use it unless you really know what you are doing. And even then you should think twice if there's a better way of doing things. –  Mjoellnir Feb 28 at 7:45
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
Depends. Unless it solves confusion, a long name ain't hurt. Eg: onRoutePresentationDisplayChanged() is very much a function from inside Android SDK –  Nilesh Pawar Apr 29 '13 at 18:45
If we had to type these method names often, the ones from the SDK present a good balance between length and being descriptive enough. However, IDEs have shortcuts to override these things and we don't really need to be calling them around, so longer descriptive names as these would have worked just nicely. This is more of a problem to beginners though. –  Daniel Jul 27 '13 at 10:46
I personally don't find your names extremely more intuitive, plus with Fragments, it doesn't really correlate. – Martín Marconcini Aug 2 '13 at 21:44
Upvoted. More helpful than the official documentation –  ronnieaka Mar 3 '14 at 5:41 
+1 good job, thank you! –  necromancer Aug 5 '14 at 3:45

No comments:

Post a Comment