Google Android Development Agency SASS

Tuesday 24 November 2009

Android Activity States and State Transitions

I wanted to tidy a bit of our Android code up recently to make sure that each Activity was handing it's state properly and to make sure that things were getting cleaned up when the Activity was done.

Before doing this it was important to fully understand the lifecycle of an Android Activity and to understand the state transitions that will and can occur within one.

An Android activity basically exists in one of four states:


Here's a bit more detail about each of these states:

Active
The Activity is in the foreground of the screen and is interacting with the user

Paused
The Activity has temporarily lost focus behind a new non-fullscreen or transparent Activity. In this state is retains all of it's state, however, if Android detects a low-memory situation it may be killed.

Stopped
The Activity is totally obscured behind another Activity. Again it retains it's state, but is much more likely to be killed at any point.

Finished
The Activity has been closed, either by Android or by calling finish(). The state it had dies at this point (unless you explicitly save it).


There are seven events in the Android Activity Lifecycle which give you a bit of control over what happens during each state transition.

onCreate(Bundle icicle)
Fires when the Activity is first launched. You would normally do all of your setup in this method. You can also retrieve any previously saved state from the supplied Bundle.

onStart()
Called when the Activity is becoming visible to the user, for example when another Activity higher in the stack has closed.

onRestart()
Called after the Activity has been stopped and is being restarted.

onResume()
Called when the Activity is becoming interactive to the user.

onPause()
Called when Android is about to start resuming another Activity. You would normally use this to stop anyting dynamic that is happening in your Activity, e.g sounds playing, animations happening.

onStop()
Called when the Activity is no longer visible, usually because another Activity has started over the top of it.

onDestroy()
This is the last breath of your Activity, called just before Android pulls the plug on it.

Here's a state transition diagram to show the sequence of states and the events in between:



No comments:

Post a Comment