You are on page 1of 17

Lesson 3.

Applications's Life Cycle

Application’s Life-Cycle .................................................................................3


Lesson 3 Application’s Life-Cycle Goals Android’s Core Components The Activity Class • • • • • .

The Service Class • • • Example 3.1 The Multitasking Golfer .

The Broadcast Receiver class • • • The Content Provider Class • • • .

Life and Death in Android • • • The Activity Stack .

Activity Life Cycle onCreate() onCreate(). onStart(). onRestart(). onPause(). onStop(). onDestroy(). onResume(). onCreate() .

onStart(). } @Override protected void onPause() { super. Example 3.onResume(). } @Override protected void onStart() { super. // The activity is about to become visible. // The activity has become visible (it is now "resumed").2 A skeleton activity showing common callback methods onCreate(Bundle saveInstanceState) onCreate public class MainActivity2 extends Activity { @Override public void onCreate (Bundle savedInstanceState) { super. // The activity is being created.onCreate(savedInstanceState). .onPause(). } @Override protected void onResume() { super.

MODE_PUBLIC) . Activity. } @Override protected void onStop() { super. } } Life-Cycle Methods onResume() onStop() Killable States • onPause().onDestroy(). // The activity is about to be destroyed. float. // The activity is no longer visible // (it is now "stopped") } @Override protected void onDestroy() { super.onStop(). string HashMap HashMaps SharedPreferences myPrefFile1 = getSharedPreferences("myPrefFile1". onStop() onDestroy() • onPause() onPause() Data Persistence using Android SharedPreferences Class <key. // Another activity is taking focus // (this activity is about to be "paused").value> key value int.

SharedPreference data/data/your-package-name/shared-prefs Example 3.3 The Life-Cycle Tour App • Toast • EditText • SharedPreferences • • •      .

com/tools" android:id="@+id/myScreen1" android:background="@android:color/white" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="matos.<?xml version="1." xmlns:tools="http://schemas. private int duration = green.MainActivity"> <EditText android:id="@+id/editColor" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Pick background color (red.csu.try clicking HOME and BACK" /> </LinearLayout> <LinearLayout> (@+id/myScreen1) public class MainActivity extends Activity { //class variables private Context" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.LENGTH_SHORT. white)" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/btnExit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Exit" /> <TextView android:id="@+id/txtSpy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" spy box . //PLUMBING: Pairing GUI controls with Java objects .

txtSpyBox = (TextView)findViewById( myScreen).id.layout. @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature( Button btnExit. } }). int count) { // nothing TODO.US). private LinearLayout myScreen. } //onCreate . private EditText txtColorSelected.OnClickListener() { @Override public void onClick(View v) { finish(). super. int after) { // nothing TODO.makeText(context. int start. txtSpyBox. int start. //wiring GUI controls and matching Java objects txtColorSelected = (EditText)findViewById(R. int count.toLowerCase(Locale. btnExit = (Button) findViewById(R.setOnClickListener(new View. "onCreate". myScreen = (LinearLayout)findViewById(R. private TextView txtSpyBox.toString(). //display the main screen ❶ setContentView(R. //show the current state's name context = getApplicationContext(). watchers. needed by interface } @Override public void beforeTextChanged(CharSequence s.myScreen1) //observe (text) changes made to EditText box (color selection) ❷ txtColorSelected. private String PREF_FILE_NAME = "myPrefFile1".onCreate(savedInstanceState). needed by interface } @Override public void afterTextChanged(Editable s) { //set background to selected color String chosenColor = s.FEATURE_ACTION_BAR).addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s. Toast.editColor).activity_main).txtSpy). } }). setBackgroundColor( btnExit. duration).setText(chosenColor). //set GUI listeners.btnExit).. int before.

} @Override ❹ protected void onStart() { super. "onStart".toString().makeText(context. "onStop".onResume(). Toast. } private void setBackgroundColor(String chosenColor. Toast. duration). "onResume". Toast. //Green100. "onDestroy". duration).contains("red")) myScreen. change background color to chosen value updateMeUsingSavedStateData().makeText(context. duration). } @Override ❸ protected void onPause() { super. } @Override protected void onStop() { super.makeText(context. RR red.@Override protected void onDestroy() { super. Toast. } @Override protected void onRestart() { super. BB blue if (chosenColor.onPause().onStop(). "onPause".makeText( //if appropriate. //Red100.onDestroy().makeText(context.makeText(context.GREEN if (chosenColor. duration).contains("green")) myScreen. saveStateData(chosenColor). Color. "onRestart".onRestart(). Color.setBackgroundColor(0xffFFCDD2). Toast. duration). } @Override protected void onResume() { super. //save state data (background color) for future use String chosenColor = Toast. duration).RED if (chosenColor.onStart(). GG green. LinearLayout myScreen) { ❺ //hex color codes: 0xAARRGGBB AA:transp.contains("blue")) .show().setBackgroundColor(0xffC8E6C9).show().

value).MODE_PRIVATE).contains("white")) myScreen. String value = txtSpyBox. }//saveStateData private void updateMeUsingSavedStateData() { ❼ // (in case it exists) use saved data telling back color SharedPreferences myPrefContainer = getSharedPreferences(PREF_FILE_NAME.setBackgroundColor(0xffffffff). setBackgroundColor(color.contains(key)) { String color = myPrefContainer. //Color.BLUE if (chosenColor.putString(key. } }//updateMeUsingSavedStateData } //Activity onCreate setContentView() btnExit txtSpyBox txtColorSelected myScreen onClick finish() TextWatcher afterTextChanged setBackgroundColor .value> table permanently kept in memory SharedPreferences myPrefContainer = getSharedPreferences(PREF_FILE_NAME.WHITE } //setBackgroundColor private void saveStateData(String chosenColor) { ❻ //this is a little <key. //Blue100. if ((myPrefContainer != null) && myPrefContainer.setText(color). Color.toString(). myPrefEditor.MODE_PRIVATE).getString(key. txtSpyBox. String key = "chosenBackgroundColor". myScreen).Editor myPrefEditor = myPrefContainer. Activity. myPrefEditor. String key = "chosenBackgroundColor". myScreen.value> to be stored represents our 'important' data SharedPreferences.getText(). Activity. defaultValue).setBackgroundColor(0xffBBDEFB).edit().commit(). //pair <key. String defaultValue = "white".

} .. } @Override public void onSaveInstanceState(Bundle outState) { .. if ( savedInstanceState != null ) String someStrValue = savedInstanceState.... .. Editable String onPause onStart setBackgroundColor() 0xFFFFCDD2 setBackgroundColor saveStateData SharedPreferenceFile SharedPreferenceFile HashMap SharedPreferenceFiles <"chosenBackgroungColor". "red"> onStart chosenBackgroundColor SharedPreferenceFile updateMeUsingSavedStateData "chosenBackgroundColor" Appendix 3. "Default"). .. outState.. "blah blah blah").putString("STR_KEY". onSaveInstanceState( outState ).getString("STR_KEY".1 Using Bundles to Save/Restore State Values Bundle STR_KEY blah blah blah @Override public void onCreate(Bundle savedInstanceState) { .

3:East] Display display = ((WindowManager) getApplication() .getDefaultDisplay(). originalOrientation = getOrientation().onPause().2 Detecting Device Rotation private int getOrientation(){ // the TOP of the device points to [0:North. . 1:West. if( getOrientation() != originalOrientation ){ // Orientation changed . //used to detect orientation change @Override protected void onCreate(Bundle savedInstanceState) { ..getRotation().WINDOW_SERVICE)) .getSystemService(Context. call onSaveInstanceState(…) }else { // no orientation change detected in the session } } . 2:South. } @Override protected void onPause() { super. } int was rotated // put a flag in outBundle.getRotation(). BackButton SharedPreferences onPause Appendix 3... return display. setContentView(R.activity_main). display..layout.