Monday 2 September 2013

Android Activity Life Cycle

Android Activity Life Cycle - 1
 Android Activity Life Cycle - 2


Android Activity Life Cycle

Hi,today i'll explain you the life cycle of android activity.Each and every activity in android maintains it's own life cycle.Android system maintains the life cycle of each activity. For understanding the life cycle of activity we have to cover three different conditions :


Android app on Google Play 
First condition is :-

User launches an application having one single activity, and after successful launch of the activity, user presses the back button of the device. So, in this situation the following methods of Activity Class will participate in lifecycle process that gets called for the launch of the activity are :

onCreate(Bundle saveState){ }
onStart(){ }
onResume(){ }

Now user can see and interact with the activity.

After that user presses the back button of the device. Now in that case activity is going to be killed by Android system and all the resources deallocation process will be done.

Methods called for this are:

onPause(){ }
onStop(){ }
onDestroy(){ }


Second Condition is :-
In second condition user launches the application by pressing the icon. The activity is on the front of user. So for this following methods gets called :

onCreate(Bundle saveState){ }
onStart(){ }
onResume(){ }

Now the activity is visible to user and user can interact with the activity.
Now there is a button on the first activity. By pressing the button user will be navigated to second activity. So in this condition android system will call following methods for the first activity :

onPause(){ }
onStop(){ }

Now user is on second activity.
After that from second activity user presses the back button of the device,so user will be navigated back to first activity. Now while again displaying the activity on the screen android will call following methods for the first activity :

onRestart(){ }
onStart(){ }
onResume(){ }

As now user is on first activity so when he again presses the back button following methods gets called :

onPause(){ }
onStop(){ }
onDestroy(){ }
Third Condition is:-


In third condition user presses the application icon to launch the application. This time our second activity is transparent. On the first activity there is a text and a button on the activity. On launch of first activity following methods get called :
onCreate(Bundle saveState){ }
onStart(){ }
onResume(){ }

Now the activity is visible to user and user can interact with the activity.
Now there is a button on the first activity. By pressing the button user will be navigated to second activity. As already mentioned the second activity is transparent so this time following methods gets called for the first activity :

onPause(){ }
Now user is on second activity. User can also see the UI content of the first activity behind the second activity but he can not interact with the components of activity.

After being on second activity now user presses the back button. So he will again move back to the first activity.
This time following methods gets called for the first activity :
onResume(){ }

As now user is on first activity. So when he again presses the back button following methods gets called :

onPause(){ }
onStop(){ }
onDestroy(){ }




Additional Condition:

We have one additional condition, which is user launches the application by pressing the application icon, and user can see the first launching activity. The methods gets called will be :


onCreate(Bundle saveState){ }
onStart(){ }
onResume(){ }

Now this time user presses the Home button of the device. So, in this conditions the methods gets called will be :


onPause(){ }
onStop(){ }

This time if android system had enough memory, then the instance of activity will not be destroyed.

Now user again launches the application. Now system will call following methods for the activity :


onRestart(){ }
onStart(){ }
onResume(){ }


As now user is on activity. So when he again presses the back button following methods gets called :

onPause(){ }
onStop(){ }
onDestroy(){ }





**IMPORTANT NOTE :-

Calling of onStop(){ } method is not sure every time during the lifecycle process of an activity. Its Behavior changes with availability of device memory.If Device is in Critical Low memory condition then it just overpasses the  onStop(){ }  method and directly calls the onDestroy() { } method directly after onPause(){ } method call. Thats Why it is Recommended that you should do Application closing time operation in onPause(){ } & not in onStop(){ }. 


OR


Answers

up vote 171 down vote accepted
See Activity Life Cycle here:
enter image description here
onCreate() :
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().
onRestart() :
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
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.
onResume() :
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().
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.
onStop():
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.
onDestroy() :
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.
EDIT:
When the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When you click on Phone button the Activity goes to the background & below events are called:
onPause()
onStop()
Exit the phone dialer & below events will be called:
onRestart()
onStart()
onResume()
When you click the back button OR try to finish() the activity the events are called as below:
onPause()
onStop()
onDestroy()

Activity States
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 3 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.
EDIT: 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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}
share|improve this answer


@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() ? – TDeBailleul Oct 31 '12 at 16:19
2  
NOT always, "onStop(): Called when you are no longer visible to the user" – Yaqub Ahmad Nov 26 '12 at 8:22
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
share|improve this answer


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 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 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 at 21:44

Once again its a personal opinion. When I explain these functions to people I explain by asking them to summiarize the meaning of the functions documented by the google SDK. And people come up with close variations of the names i suggested. – Nilesh Pawar Aug 6 at 1:42

For example: 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. Isnt this a natural candidate for onVisible() ? – Nilesh Pawar Aug 6 at 1:44
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 3 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.
Paused Activity gets Resume and Stopped get Restarted.
When you call this.finish() onPause-onStop-onDestroy will be called. The main thing to remember..Paused Activities get Stopped and Stopped activity gets Destroyed whenevery Android requires memory for other operations.
Hope it's clear enough.