Managing Activity State

Applications can be interrupted when various higher-priority events, such as phone calls, take precedence. There can be only one active application at a time; specifically, a single application activity can be in the foreground at any given time.

Android applications are responsible for managing their state, as well as their memory, resources, and data. The Android operating system may terminate an activity that has been paused, stopped, or destroyed when memory is low. This means that any activity that is not in the foreground is subject to shutdown. In other words, an Android application must keep state and be ready to be interrupted and even shut down at any time.

Using Activity Callbacks

The Activity class has a number of callbacks that provide an opportunity for an activity to respond to events such as suspending and resuming. Table 3.1 lists the most important callback methods.

TABLE 3.1 Key Callback Methods of Android Activities

Callback Method




Called when an activity

Initializes static activity data.

starts or restarts.

Binds to data or resources required. Sets layout with setContentView().


Called when an activity

Acquires exclusive resources.

becomes the foreground

Starts any audio, video,


or animations.


Called when an activity

Saves uncommitted data.

leaves the foreground.

Deactivates or releases exclusive resources.

Stops any audio, video, or animations.


Called when an

Cleans up any static activity

application is shutting



Releases any resources acquired.

The main thread is often called the UI thread, because this is where the processing for drawing the UI takes place internally. An activity must perform any processing that takes place during a callback reasonably quickly, so that the main thread is not blocked. If the main UI thread is blocked for too long, the Android system will shut down the activity due to a lack of response. This is especially important to respond quickly during the onPause() callback, when a higher-priority task (for example, an incoming phone call) is entering the foreground.

Figure 3.2 shows the order in which activity callbacks are called.


Important callback methods of the activity life cycle.

Figure 3.2 shows the order in which activity callbacks are called.

Saving Activity State

An activity can have private preferences—much like shared application preferences. You can access these preferences by using the getPreferences() method of the activity. This mechanism is useful for saving state information. For example, PlayActivity for your game might use these preferences to keep track of the current level and score, player health statistics, and game state.

0 0

Post a comment