Activity Life Cycle

The activity is the core of an android application. Each application can have one or more activities.

In this post we are going to explore the activity’s life cycle and understand the event handler of each stage through the activity’s life cycle.

Activities in the system are managed in an activity stack (Last in Last out). When a new activity is launched it becomes on the top of the stack. Any previous activity will be below it and won’t come to the top until the new one exists.

The application on the top of the stack has the highest priority from the operating system. While the activity that is not visible has lower priority even if the a running activity requires more memory, the system can shut down that activity to free memory.

Android runs each activity in a separate process each of which hosts a separate virtual machine. Android saves metadata (state) of each activity so that when a new activity launches so that it can come back to the activity when the user backtracks.

The activity can be in one of four states:

Active: the activity started, is running and is in the foreground.

Paused: the activity is running and visible but another activity (non full sized) is running on the top or a notification is displayed. The user can see the activity but can not interact with it. A paused activity is fully alive (maintains state and member information) but can be killed by the system in low memory situations.

Stopped: the activity is running but invisible because the user has launched another activity that comes to the foreground the activity is alive (maintains state and member information) but can be killed by the system in low memory situations.

Dead: either the activity is not started or it was in pause or stop state and was terminated by the system to free some memory or by asking the user to do so.

The following figure shows the states of the activity and the methods that handle each state

The sequence is as follows:

  • The activity starts, passes through onCreate(), onStart() the activity is still not visible to the user, onResume() then it comes to the foreground and becomes fully running.
  • If another activity launches or a notification appears the activity passes through the onPause() method. Then there would be two scenarios:
    1.if the system decides to kill your activity due to low memory the activity starts the cycle again from onCreate() method with Bundle savedInstanceState parameter that holds data about the previous state of the activity.
    2.If the user resumes the activity by closing the new activity or the notification the activity cycle continues from the onResume() method

  • When the user is about to close the activity the activity calls onStop() method then onDestroy() method when the system destroys the activity.
    But if another activity runs while the current one is was not shut, the activity calles onStop() method and if it is not killed by the system it will call onRestart() method then onStart() mehod and continues the cycle.

  • onCreate(): will be invoked in three cases:
    - the activity runs for the first time and it will be invoked with null Bundle savedInstanceState parameter.
    - the activity has been running then stopped by the user or destroyed by the system then it would be invoked with Bundle savedInstanceState that holds the previous state of the activity.
    - the activity is running and you set the device to different resources like Portrait vs landscape, then the activity will be recreated.

    in this method you will create the user interface, bind data to controls and register the event handlers for the controls. Then it is followed by onStart() method.

  • onStart(): will be invoked when the activity is first launched or brought back to the foreground
    it would be followed by onResume() if the activity continues and comes to foreground, or by onStop() if the activity is killed.
  • onRestart(): is invoked in case the activity has been stopped and is about to be run again. Always followed by onStart() mehod.
  • onResume(); invoked when the activity is about to come to the foreground and is on the top of the activity stack. It is the place where you can refresh the controls if the activity is using a service that displays some feeds or news. Always followed by onPause() method.
  • onPause(): is invoked when another activity launches while the current activity is launched or when the system decides to kill the activity. In this method you have to cancel everything you did in onResume() method like Stopping threads, stopping animations or clearing usage of resources(eg the camera).

    This method is followed by onResume() if the activity returns back to front or by onStop() if the activity is to be invisible.
  • onStop(): is invoked when a new activity is about to come over the current one or the current one is to be destroyed. Always followed by onResume() if the activity comes back or onDestroy if the activity is to be killed.
  • onDestroy():is invoked when the activity is shutting down because the activity called finish() [terminated the activity] or because the system needs memory so it decided to kill the activity.
Killable methods:

There are methods that are “killable” meaning that after theses methods return, the process hosting them can kill the activity without executing any further code (due to lack of memory)

These methods are onPause(), onStop() and onDestroy()

  • The entire activity life cycle is between the onCreate() where you construct the UI and aquire resources and onDestroy() method where you release all resources.
  • The visible life time of the activity is between onStart() and onStop(). Between the activity is visible to the user although he may be unable to interact with it. Between the two methods you persist the state of the activity so that if another one comes to the foreground then comes back to the original activity you find the state persisted.
  • The foreground lifetime is between the onResume() and on Pause(). During this time the activity is fully interactive with the user. The activity can go through the resume and pause states many times (if the device sleeps or a new activity launches) so the code should be very lightweight.


Google Nexus One Vs. iPhone 3GS

Google released a new Android phone:
The Google Nexus One
here is an interesting comparison between it and the iphone
looking forward to read your opinions


Hello Android

Now we’re going to explore our first Android application which will be the famous Hello World application. We are going to explain the structure of an Android application and some of the basic concepts wee must understand
  1. Open Eclipse and select from the menu File>New>Android Project, you’ll see a window like this.
  2. Now there are several fields that appear here they are:
    Project Name: The Eclipse project name, the name of the folder that will hold the project files.
    Application Name:The name of the application that will appear on the phone.
    Package Name: The package name space, it sould be in the form of [abc].[xyz].
    Create Activity: the name of the basic activity class of your application. it’s optional to create.
    Min SDK Version: the minimum API level required by the application. You see in the Build Target list there is a list of the available SDK versions to use for the application and in front of each one the corresponding API level. You must ensure that you application API level is supported b the device.
  3. Press Finish then press run and choose run as Android Application, the emulator will start, wait until the main screen appears, unlock by pressing the menu button then you should see something like this

    Notice: the emulator may take a long time to boot so please be patient.
  4. Now go to the package explorer on the left bar of eclipse to your project

    folder navigate to src/[PackageName]/ this is the main activity class of your application. It should be like this:
    import android.os.Bundle;
    public class HelloAndroid extends Activity {
        /** Called when the activity is first created. */
        public void onCreate(Bundle savedInstanceState) {

  5. We will explain what each line in this code means later but now let’s understand what each folder in our project contains.
  6. The project contains the following folders

    Folder Name




    Contains all the source code (class files) for the project



    Contains the class file

    Generated automatically

    Android 1.5

    Its name changes according to the sdk version you use (1.5 here). Contains the Android API class files packed in android.jar files

    Generated automatically


    You can place any external resources (text files,images,…) in this folder. It’s much like the res file except it’s more like the file system where you put files that you want to access them as raw bytes



    Contains resources for the application



    Contains the images required for you application. You can add your own image files to this folder



    Contains the main.xml file that defines the view that construct the User Interface of the application



    Contains other resources that can be used for your application such as string resources, styles or colors


  7. So that was a quick look on the android project structure, in this post we will take a deeper look on the hello Android application.


Colors, Arrays and Dimensions Resources

Android provides three other types of resources that can be defined as XML files in the res/values folder. These resources can be Colors, Arrays and Dimensions.

Color Resources:
You can define XML files that contain definitions for colors that can be used in your application.

Colors in Android are hexadecimal RGB values, also optionally specifying an alpha channel (transparency).

You have your choice of single-character hex values or double-character hex values, leaving

you with four styles:

  • #RGB (Red: #F00).
  • #ARGB (Red with Alpha 5: #5F00).
  • #RRGGBB (Red : #FF0000).
  • #AARRGGBB (Red with Alpha 50: 50FF0000 #).
You define colors in the xml file as follows:

<color name="Red">#FF0000</color>
You can use it from code behind as this:
TextView txtColor=(TextView)findViewById(;

or from the layout as this:

Dimensions Resources:
You can define Dimension resources to use them with your widgets to define padding, width or height.

The dimension resources can be defined in the following units:

  • Pixels: (px).
  • Inches: (in).
  • Millimeters: (mm).
  • Points: (pt).
  • Density: (dp) density-independent pixels based on 160 dpi (dot per inch).
  •  Scale: (sp) Scale-independent pixels (dimensions that allow for user sizing; helpful for use in
To define dimension resources in xml files you can write it like this:

<dimen name="PixelDim">10px</dimen>
<dimen name="PointsDim">10pt</dimen>
<dimen name="InchesDim">0.2in</dimen>
<dimen name="MilliDim">5mm</dimen>
<dimen name="DensityDim">20dp</dimen>
<dimen name="ScaleDim">20sp</dimen>

And you can use them from the xml layout definition like this

or from code like this:
TextView txtdp=(TextView)findViewById(;

Array Resources:
Array resources allow you to define custom string arrays that hold values you can use in your application such as a countries list or a list of names.

An Array resource is defined using string-array element while items are defined using item element.

<string-array name="countries">

and you can use them from code like this:
String [] Countries=this.getResources().getStringArray(R.array.countries);
you can define more than one string-array in the same file

that was all about color, dimensions and arrays in android

Download sample application from here


Image Resources

Android provides us with the ability to use image resources in our applications. We can put image files in res/drawable directory and access them from the xml layout or by the generated ID from class file.

You can use image files of the following formats:
  • PNG
  • JPEG
  • GIF
Notice that there are two restrictions:
  • If you use two files with the same base name you will receive an error. You cannot use two files like Hello.jpeg and Hello.png.
  • If you create any subdirectory under res/drawable directory any image files in it will be ignored.
Now let’s demonstrate how can we use image resources

We will place an image called android.jpeg in res/drawable directory

We can use it from xml layout as this
<imageview android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/android" /%gt;

Or from code as this
ImageView img=(ImageView)findViewById(;

or like this to get the image as a drawable object

ImageView img2=(ImageView)findViewById(;
Drawable drawable=this.getResources().getDrawable(;

Color drawable Resources:
You can define XML files that contain definitions for color drawable resources which are color rectangles that can be used as backgrounds

You can define the color drawable resources in values/strings.xml file or by creating a custom xml file to hold these resources

You define color drawable resources like this:
<drawable name="redBox">#f00</drawable>
You can use it from xml layout like this

Or from code like this:
TextView txt=(TextView)findViewById(;

or like this:
ColorDrawable drawable2=(ColorDrawable)this.getResources().getDrawable(R.drawable.redBox);

or this
notice that if the textview does not have text the background color will not appear.

Download a demo application from here


Understanding String Resources

Android offers three types of string resources: Plain Strings, string formats and styled texts

Plain string resources can be declared in res/values/strings.xml

If you create an Android application [for example call it HelloAndroid] and just before adding anything, browse to res/values/strings.xml it will be like this:

    Hello World, HelloAndroid!

This is a pretty example of Plain text resources. The resource with name=”app_name” is the name of the application that appears when you deploy the application to the phone, it’s referenced in the AndroidManifest.xml file in the application tab. You can change it as you want.
Now let’s add two entries in the file to see how can we use plain text resources within the application
This is referenced from the res/layout/main.xml
This is referenced from the code
The first string will be the text of a text view defined in res/layout/main.xml file

See that to reference the first string we use the @string/[Resource Name] convention.
The second resource will be referenced from the code file of the activity like this
TextView txtHeader2=(TextView)findViewById(;
if you open file of your project you will find that Android has generated a class called string with members referencing to your string resources:
public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
        public static final int plainResource1=0x7f040002;
        public static final int plainResource2=0x7f040003;

Also notice the way you access the string resources in Android, you don’t open the strings.xml file and parse it t extract the values you want to reference- instead you access them through the R.string class defined in R.Java and Android does the rest for you.

Also another interesting feature is that you can define your own resources file, go to res/values/ directory, right click>New>File and call the file for example CustomStrings
You will see something like this:

You can define resources manually by choosing the CustomStrings.xml tab or by using clicking Add button and adding the name and the value of the resource.
I will add a resource with the name CustomString and value this is a custom string and reference them from the layout like this

Or from the code like this:
TextView txtHeader3=(TextView)findViewById(;

String format Resources:

the dalvik vm offers string formats whih provide placeholders representing data to be replaced at runtime by variables
an example of a string format resource is:
This is resource for %1$s
the %1$s is the place holder that would be replaced by a variable string.
and from your code you can use it like this:
//String format resource
        TextView txtHeader4=(TextView)findViewById(;
        String strFormat=getString(R.string.StringFormat);
        String header=String.format(strFormat, "Giving an example of string format resource");

and the text view will have a text equal to This is resource for Giving an example of string format resource.

Styled text Resources:
You can use string resources styled with these three HTML tags:
<b>,<u> and <i>

You can define the a string as follows:
This is an <u>example</u> of <i>Styled</i> <b>Resources</b> 

And use it from the code as this:
TextView txtHeader5=(TextView)findViewById(;

notice that we use setText() method by calling the string resource directly.
if we use the getString() method it will display the string without styling
we can use the HTML styled text also by using spanned.
Spanned textSpan = android.text.Html.fromHtml(htmlTaggedString);
//Set it in a text view

Android provides three types of string resources: Plain strings, String formats which provide place holders to be replaced by variables in runtime and Styled text resources which provide styling with three standard HTML tags
Download a demo application here


Understanding Resources

Resources in Android are files stored under the res directory of your project. Resources can be physical files (Audio, video, images, text, etc…) or xml files that declare some values to use in your application.

Why use Resources:
  1. The resources are bound to the application in a way that you can change them without needing to change the source code or recompile the application.
  2. The Android Generates an ID for each resource file so you can access them directly and easily. All the resources IDs are added to the R.Java file.
  3. When you use XML resource files, Android pareses these files automatically so you can reference values defined in them directly with no extra effort.
  4. Using resources is very useful in Localization and Internationalization of the application in case you develop multilingual applications. This includes not just the labels but it can include alignment, directions images or any kind of files.
Types of resources:
  • Strings, colors, arrays, dimensions. Defined in res/values/ directory. Using them is very useful in Localization and Internationalization.
  • Images put in res/drawable directory. You can put all the images or icons you need in your application.
  • Animations, defined in res/anime/ directory. You can define animations that for example correspond to a button click.
  • XML, defined in res/xml/ directory for xml files containing your custom data.
  • Layout resources, defined in res/layout/ for declaring the views that construct the user interface of the activities.


Understanding Assets

Android provides the assets folder to put files that you want to include with the package. The files in assets folder do not generate an ID in file. You access them in the same way you access files on the file system in any programming language.

The code below is a program that reads the content of a text file (Hello.txt) in the assets folder

The text file has the line “Hello Android”





import android.content.res.AssetManager;

import android.os.Bundle;

import android.widget.ImageView;

import android.widget.TextView;

public class HelloAndroid extends Activity {

/** Called when the activity is first created. */


public void onCreate(Bundle savedInstanceState) {


//Set the Content View


TextView txtHeader=(TextView)findViewById(;

TextView txtContent=(TextView)findViewById(;

//Gets the instance of the asset manager

AssetManager mngr=getAssets();

//Get file names of files in the assets



String [] files=mngr.list("Files");


//Read contents of the text file


String text=ReadFile(is);



catch (IOException e) {



catch (Exception e) {




String ReadFile(InputStream is)


ByteArrayOutputStream bo=new ByteArrayOutputStream();

byte [] buffer=new byte[1024];







catch(IOException e)



return bo.toString();



After running the application it should be like this:


Explaining Hello Android application

Now we’re going to take a deeper look on the Hello Android application and know what each line of code exactly means
The file contains the following code:

import android.os.Bundle;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

  1. The first line is the package name of the application.
  2. Lines 3,4 are import statements of two libraries():
  3. Line 6 is the declaration of the HelloAndroid class which extends from
    , Activity represents the User interface of your application much like windows or web forms.
  4. Our class contains one function which is onCreate(Bundle savedInstanceState). This function is called when the activity is first created, it should contain all the initialization and UI setup.
    This function has a parameter savedInstanceState of type Bundle
    this object holds the activity’s previously saved state if exists (similar to view state concept)
  5. Line 10 calls the super class’ OnCreateMethod with the activity’s

  6. Line 11 calls
    method which dsiplays the layout definition in main.xml file in res/layout directory by accessing a reference to it from the R class
    This method is required to display the user interface, if the activity does not include this function then it would display a blank screen

The basic android application with only one view consists of a class that extends the Activity class. This class preserves the activity frozen state (like viewstate in and it displays the UI defined in xml file or defined explicitly programmatically.