Unit I - Monitoring State Changes
Unit I - Monitoring State Changes
To ensure that Activities can react to state changes, Android provides a series of event handlers that are fired
when an Activity transitions through its full, visible, and active lifetimes.
onCreate()
onRestart()
onStart()
onResume()
onPause()
onStop()
onDestroy()
package com.paad.activities; // Called at the start of the visible lifetime.
@Override
import android.app.Activity; public void onStart(){
import android.os.Bundle; super.onStart();
// Apply any required UI change now that the
public class MyStateChangeActivity extends Activity is visible.
Activity { }
// Called at the start of the full lifetime.
// Called at the start of the active lifetime.
@Override
@Override
public void onCreate(Bundle savedInstanceState)
public void onResume(){
{
super.onResume();
super.onCreate(savedInstanceState);
// Resume any paused UI updates, threads, or
// Initialize Activity and inflate the UI.
processes required
}
// by the Activity but suspended when it was
inactive.
// Called after onCreate has finished, use to
}
restore UI state
@Override
// Called to save UI state changes at the
public void onRestoreInstanceState(Bundle
// end of the active lifecycle.
savedInstanceState) {
@Override
super.onRestoreInstanceState(savedInstanceStat
public void onSaveInstanceState(Bundle
e);
savedInstanceState) {
// Restore UI state from the savedInstanceState.
// Save UI state changes to the
// This bundle has also been passed to onCreate.
savedInstanceState.
// Will only be called if the Activity has been
// This bundle will be passed to onCreate and
// killed by the system since it was last visible.
// onRestoreInstanceState if the process is
}
// killed and restarted by the run time.
super.onSaveInstanceState(savedInstanceState);
// Called before subsequent visible lifetimes
}
// for an Activity process.
@Override
// Called at the end of the active lifetime.
public void onRestart(){
@Override
super.onRestart();
public void onPause(){
// Load changes knowing that the Activity has
// Suspend UI updates, threads, or CPU intensive
already
processes
// been visible within this process.
// that don’t need to be updated when the
}
Activity isn’t
// the active foreground Activity.
super.onPause(); super.onStop();
} }
// Sometimes called at the end of the full
// Called at the end of the visible lifetime. lifetime.
@Override @Override
public void onStop(){ public void onDestroy(){
// Suspend remaining UI updates, threads, or // Clean up any resources including ending
processing threads,
// that aren’t required when the Activity isn’t // closing database connections etc.
visible. super.onDestroy();
// Persist all edits or state changes }
// as after this call the process is likely to be }
killed.
Within an Activity’s full lifetime, between creation and destruction, it goes through one or more iterations of
the active and visible lifetimes.
The full lifetime of Activity occurs between the first call to onCreate and the final call to onDestroy.
It’s not uncommon for an Activity’s process to be terminated without the onDestroy method being
called.
Use the onCreate method to initialize Activity:
• inflate the user interface,
• get references to Fragments,
• allocate references to class variables,
• bind data to controls, and
• start Services and Timers.
If the Activity was terminated unexpectedly by the runtime, the onCreate method is passed a Bundle
object containing the state saved in the last call to onSaveInstanceState.
should use this Bundle to restore the UI to its previous state, either within the onCreate method or
onRestoreInstanceState.
Override onDestroy to clean up any resources created in onCreate, and ensure that all external
connections, such as network or database links, are closed.
The rapid creation and destruction of objects force additional garbage collection, a process that can
have a direct negative impact on the user experience.
If Activity creates the same set of objects regularly, consider creating them in the onCreate method
instead, as it’s called only once in the Activity’s lifetime.
An Activity’s visible lifetimes are bound between calls to onStart and onStop.
Between these calls Activity will be visible to the user, although it may not have focus and may be
partially obscured.
Activities are likely to go through several visible lifetimes during their full lifetime because they move
between the foreground and background.
Although it’s unusual, in extreme cases the Android run time will kill an Activity during its visible
lifetime without a call to onStop.
The onStop method should be used to pause or stop animations, threads, Sensor listeners, GPS
lookups, Timers, Services, or other processes that are used exclusively to update the UI.
There’s little value in consuming resources (such as CPU cycles or network bandwidth) to update the
UI when it isn’t visible.
Use the onStart (or onRestart) methods to resume or restart these processes when the UI is visible
again.
The onRestart method is called immediately prior to all but the first call to onStart. Use it to
implement special processing that you want done only when the Activity restarts within its full
lifetime.
The onStart/onStop methods are also used to register and unregister Broadcast Receivers used
exclusively to update the UI.
The active lifetime starts with a call to onResume and ends with a corresponding call to onPause.
An active Activity is in the foreground and is receiving user input events.
Activity is likely to go through many active lifetimes before it’s destroyed, as the active lifetime will
end when a new Activity is displayed, the device goes to sleep, or the Activity loses focus.
Try to keep code in the onPause and onResume methods relatively fast and lightweight to ensure
that application remains responsive when moving in and out of the foreground.
Immediately before onPause, a call is made to onSaveInstanceState.
This method provides an opportunity to save the Activity’s UI state in a Bundle that may be passed
to the onCreate and onRestoreInstanceState methods.
Use onSaveInstanceState to save the UI state (such as checkbox states, user focus, and entered but
uncommitted user input) to ensure that the Activity can present the same UI when it next becomes
active.
You can safely assume that during the active lifetime onSaveInstanceState and onPause will be called
before the process is terminated.
Most Activity implementations will override at least the onSaveInstanceState method to commit
unsaved changes, as it marks the point beyond which an Activity may be killed without warning.
Depending on application architecture you may also choose to suspend threads, processes, or
Broadcast Receivers while Activity is not in the foreground.
The onResume method can be lightweight.
You do not need to reload the UI state here because this is handled by the onCreate and
onRestoreInstanceState methods when required.
Use onResume to reregister any Broadcast Receivers or other processes you may have suspended in
onPause.
ActivityLifeCycleExampleApplication:
MainActivity.java
public class MainActivity extends Activity {
String tag="ActivityLifeCycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(tag,"onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.i(tag,"onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.i(tag,"onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.i(tag,"onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.i(tag,"onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(tag,"onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(tag,"onDestroy invoked");
}
}
The Android SDK includes a selection of Activity subclasses that wrap up the use of common UI widgets.
MapActivity — Encapsulates the resource handling required to support a MapView widget within an
Activity.
ListActivity — Wrapper class for Activities that feature a ListView bound to a data source as the
primary UI metaphor, and expose event handlers for list item selection.
ExpandableListActivity — Similar to the ListActivity but supports an ExpandableListView.