Understanding the Life Cycle of Activities in Android

Tweet

An “activity” in Android is a single screen in which the user will interact. If you want to create a form to take input from the user, or if you need to display information or feedback to the user, you would usually build an activity for the purpose.

In some circumstances, an activity will be running on the user’s phone (or any other Android device) and they might want to switch to some other task. Android runtime will put your initial activity in the background in those kinds of scenarios. When there are many activities and the android runtime is low on resources, it might destroy your activity depending on its priority (the activity with which the user is interacting currently always has the highest priority).

So, depending on the situation, once your activity is launched, Android runtime might handle your activities in a number of different ways. When the state of your activity changes, Android runtime calls specific events (functions) that allow your activity to perform certain tasks before its state is changed. In this article, we are going to examine the different states in which an activity can be, the different events that are executed during the lifetime of an activity, and what a well-designed activity can and should perform during those events.

 States of An Activity

During its lifetime, an Android activity will be in one of the following states:

  • Active – An activity is in an active state when it is in direct interaction with the user in the foreground of the Android device.
  • Inactive – An activity is in an inactive state before it is launched or once it has been “killed” by the android runtime.
  • Paused – An activity is in a paused state when the activity is visible but not in focus.
  • Stopped – An activity is in a stopped state when it’s no longer visible. It is still in memory, but it could be destroyed by the android runtime, as “stopped” activities are generally considered low priority.

Activity Life Cycles

When the activity changes states, the Android runtime calls different even handlers on the activity. The default implementations of these even handlers are already present in the Activity class. Depending on the needs of your activity, you can override any of the following even handlers.

To understand the event handlers, let’s create a simple Activity called as ActivityLifeCycleDemo. The default activity will look as follows:


public class ActivityLifeCycleDemo extends Activity {

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

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

}

Now, I’ll add two support functions that we are going to use with our activity. Within the class, first define a final “int”, and then follow with the functions:


static final int NOTIFICATION_ID = 1776;

protected void DisplayNotification(String title,String message)

{

NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification note = new Notification(R.drawable.icon, title, System.currentTimeMillis());

PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, ActivityLifeCycleDemo.class), 0);

note.setLatestEventInfo(this, title, message, intent);

notifManager.notify(NOTIFICATION_ID, note);

}

protected void sleepForaMinute()

{

try

{

Thread.sleep(60000);

} catch (InterruptedException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

In the above example, function “DisplayNotification” will simply display a notification using the Android’s standard notification classes. The function “sleepForaMinute” just sleeps for a minute so that we can see the events in case they happen very quickly.

onCreate

Let’s first override the onCreate handler as follows:


public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

DisplayNotification("ActivityLifeCycleDemo","onCreate");

sleepForaMinute();

}

Now, when you start your activity, you should see the notification shown below on your Android device.

In our onCreate handler, we set the main content view and display the notification to signify that this event handler is called. The onCreate handler is called whenever a new activity is created. In your onCreate handler, you should include all of the typical initializing tasks like creating the UI, acquiring some resources, creating services, etc.

The onCreate method even passes the savedInstanceState; It can read values and assist with the initializing of the UI and other basic tasks. Almost all activities will require you to override this method.

onDestroy

Now let’s override the onDestroy event as follows:


@Override

<strong>protected</strong> <strong>void</strong> onDestroy() {

super.onDestroy();

DisplayNotification("ActivityLifeCycleDemo","onDestroy");

}

The onDestroy event is called whenever the activity is destroyed. If you start an activity and then press the back button, the activity will be destroyed and you should see the following notification.

The onDestroy method should clean up all the resources those were acquired by the onCreate method and previously used by the now-destroyed activity.

onStart

Now let’s override the onStart method as follows:


@Override

protected void onStart() {

super.onStart();

DisplayNotification("ActivityLifeCycleDemo","onStart");

sleepForaMinute();

}

The onStart event is called whenever the activity becomes visible. When you start a new activity, the onStart event will be called after the onCreate event. If the activity becomes invisible (when the user starts another activity) and then becomes visible once again, the onStart event will be called (onCreate will not be called in this case; it’s reserved for brand new activities). The following notification will be seen whenever the activity changes from an invisible to a visible state.

In the onStart method, you should start all the visible actions necessary for your activity, like showing animations, displaying user prompts, etc.

onStop

Now, let’s override the onStop method as follows:


@Override

protected void onStop() {

super.onStop();

DisplayNotification("ActivityLifeCycleDemo","onStop");

}

The onStop event is executed whenever an activity becomes invisible. So, if you have you activity started, andclick on the home button (making your current activity invisible), you should see the following notification.

The onStop method should stop all of the actions that were started in the onStart method. Because the activity is invisible, your activity should not be performing (and consuming CPU cycles for) any tasks required for the Android interface.

onResume

Now let’s override the onResume method as follows:


protected void onResume() {

super.onResume();

DisplayNotification("ActivityLifeCycleDemo","onResume");

}

The onResume event happens just before the activity is made visible and becomes ready to take user inputs once again. When the activity starts or comes back into focus, you will see the following notification.

You should keep the code in onResume very quick, because it will be called quite frequently. If you build onResume inefficiently, you might end up with a slow, unresponsive Android app.

onPause

Now let’s override the onPause method as follows:


@Override

protected void onPause() {

super.onPause();

DisplayNotification("ActivityLifeCycleDemo","onPause");

}

onPause is called whenever an activity goes out of focus. The code in onPause (like onResume) should be very quick, as it might get called frequently.

onSaveInstanceState

onSaveInstanceState is an event that can be used to save the state of the activity in a Bundle. That Bundle will be passed either to the event onRestoreInstanceState or onCreate, both of which can read from the Bundle and restore the state of the activity.

Conclusion

An Android activity goes through several different states during its lifetime. Understanding the states and the events will help you to code your app in a more efficient, responsive way for your users. The Android operating system, by calling events on the activity, lets the activity manage itself quite effectively, as long as you’re developing the different events carefully. So, have fun while managing the life cycle of your next Android app!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments