Android Activity Life Cycle

We had a quick glance on “What an android activity is?” in our previous post, here we are going to discuss about Life cycle involved in an android activity.

Activity in the system is managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity — the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits. It might be little bit confusing, let me explain it with an example:

Assume you open Facebook app in your android mobile, you are looking through the shares/posts posted by your friends and you are coming across one interesting web link posted by your friend. You click on the link to view what is there inside, it takes you to web browser and open up the website. If you look at the android activity stack level, facebook activity is now placed below the browser activity in activity stack and facebook activity will come to foreground only when browser activity is closed. So the state of facebook activity is saved and will be used when it move to top of the stack.

Hope you got the meaning out of what I am trying to say.

Android activity life cycle is controlled by life cycle methods and we will see below what they do:

The onCreate method is called after an Activity instance has been created. This is where most applications perform most of their initialization: reading in the layouts and creating View instances, binding to data, and so on. Note that, if this Activity instance has not been destroyed, nor the process killed, this is not called again. It is called only if a new instance of an Activity class is created. The argument to this method is a Bundle object that contains saved application state. If there is no saved state, the value of this argument is null.
The onRestart method is called only if an activity has been stopped. “Stopped” means the activity is not in the foreground, interacting with the user. This method is called before the onStart method.
The onStart method is called when the Activity object and its views become visible to the user.
The onResume method is called when the Activity object and its views become interactive with the user.
The onPause method is called when a different Activity instance is going to be visible and the current Activity has stopped interacting with the user.
The onStop method is called when an activity is no longer visible to, or interacting with, the user.
The onDestroy method is called when an Activity instance is going to be destroyed—no longer used. Before this method is called, the activity has already stopped interacting with the user and is no longer visible on the screen. If this method is being called as the result of a call to finish, a call to isFinishing will return true.
This is where an application gets a chance to save instance state. Instance state should be state that is not persisted with an pplication’s data model, such as the state of an indicator or other state that is only part of the Activity object. This method has an implementation in the parent class: it calls the onSaveInstance State method of each View object in this instance of Activity, which has the result of saving the state of these View objects, and this is often the only state you need to store this way. Data that your subclass needs to store is saved using the “put” methods of the Bundle class.
The onRetainNonConfigurationInstance method is called after onStop, which means there is no guarantee it will be called, nor even, if it is called, that the reference returned will be preserved and provided to the subsequent Activity instance. The getLastNonConfigurationInstance() method can be called in the onCreate method, or subsequently when restoring activity state.

Before you proceed with the code, give a glance at the Android life cycle-State diagram given in the Android developers site. You will understand the inter relationship between different states of an android life cycle.

Quick Links

Project Structure

  • Create a new Android project
  • Replace the default activity code with the one given above
  • Make sure your eclipse editor shows Logcat in fast view. If it is not showing, choose logcat [ Windows >> Show view >> Others >> Android >> Logcat ]
  • Run the application using emulator or device.

Code Listings

Take a look at the below program to see what kind of information and in what order the information is logged:

package com.prgguru.android;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class ActivityLifeCycleActivity extends Activity {
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
// The string "fortytwo" is used as an example of state
private final String state = "fortytwo";

@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
String answer = null;
// savedState could be null
if (null != savedState) {
answer = savedState.getString("answer");
}
Log.i(TAG, "onCreate"
+ (null == savedState ? "" : (RESTORE + " " + answer)));
}

@Override
protected void onRestart() {
super.onRestart();
// Notification that the activity will be started
Log.i(TAG, "onRestart");
}

@Override
protected void onStart() {
super.onStart();
// Notification that the activity is starting
Log.i(TAG, "onStart");
}

@Override
protected void onResume() {
super.onResume();
// Notification that the activity will interact with the user
Log.i(TAG, "onResume");
}

protected void onPause() {
super.onPause();
// Notification that the activity will stop interacting with the user
Log.i(TAG, "onPause" + (isFinishing() ? " Finishing" : ""));
}

@Override
protected void onStop() {
super.onStop();
// Notification that the activity is no longer visible
Log.i(TAG, "onStop");
}

@Override
protected void onDestroy() {
super.onDestroy();
// Notification that the activity will be destroyed
Log.i(TAG, "onDestroy "
// Log which, if any, configuration changed
+ Integer.toString(getChangingConfigurations(), 16));
}

@Override
protected void onSaveInstanceState(Bundle outState) {
//Save instance-specific state
outState.putString("answer", state);
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}

@Override
public Object onRetainNonConfigurationInstance() {
Log.i(TAG, "onRetainNonConfigurationInstance");
return new Integer(getTaskId());
}

@Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
// Restore state; we know savedState is not null
String answer = null != savedState ? savedState.getString("answer")
: "";
Object oldTaskObject = getLastNonConfigurationInstance();
if (null != oldTaskObject) {
int oldtask = ((Integer) oldTaskObject).intValue();
int currentTask = getTaskId();
// Task should not change across a configuration change
assert oldtask == currentTask;
}
Log.i(TAG, "onRestoreInstanceState"
+ (null == savedState ? "" : RESTORE) + " " + answer);
}
}

Now you could see the set of log messages in ‘Logcat’ window. In order to generate interesting logging information, you can start other applications and go back and forth, using the application switcher or the Launcher to return to the Finch application.

[pgsubscribe]

Start enough other applications, and on returning to the Finch application,you will see that the process ID, or PID, has changed, but the application appears to be in the same state as you left it. This is because state was restored for this activity, and all other components of the application, from the saved state.

OK, it’s time to dig the log messages:

Demo

I just ran the application in my Android device, the log message generated in the Logcat was:

Application which I am seeing in mobile is:

Now I am opening another application[Profiler app], you can open any installed application. We just gonna test how the states behave when we move from one app to another:

See what happened by reading the below log message, our application’s state is saved and application is paused for now.  The application’s state will be reused when we come back to our application:

I closed the Profiler app and returning back to my application:

[pglinkadssmall1]

I pressed ‘Home’ button of the android device, my application is still running:

I re-opened the application as it was below in the android activity stack, now it has been moved to top of the stack. Associated log messages:

I pressed back button which close the application and the corresponding log message:

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file simliar to exe in windows.

 


[pglinkadssmall]
Share with your friends if you feel this post is interesting!! :)

Reference:

Android activity lifecycle

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Android Guru

Share This Post On
  • NIKHIL RAJ L R

    Nice.. :)

  • Very nice and useful for beginners. Actually I too am a beginner in Android and wish to get through in android programming. Your blog has helped me a lot. Thanks for sharing.

    Android developers

    • Thanks for your feedback. Spread a word about this blog to your friends who are interested in Android development.

  • Pingback: Android Game Development 101[Part 4: Working with Android APIs] | Salamonia()

  • asteriskcoder

    Great explanation in textual way but this video explains stuff even better. In fact the best tutorials on Android I have seen online
    https://www.youtube.com/watch?v=jx0i36cqXXc

  • Rakesh

    Nice Article It helped me lot
    Thank You,

  • Minu

    I have a doubt.
    When we move from one activity to another i.e first activity is not visible now, thn why onStop() is not called at that time?

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares