Professional Documents
Culture Documents
Chapter03 Life Cycle - Publish
Chapter03 Life Cycle - Publish
Anatomy of Android applications Core components are the primordial classes or building blocks from which apps are made.
Component’s life cycle An application consists of one or more core component objects, working in a cooperative mode, each
contributing somehow to the completion of the tasks
Application’s life cycle
Each core component provides a particular type of functionality and has a distinct lifecycle.
Example
MOBILE DEVELOPMENT A lifecycle defines how the component is created, transitioned, and destroyed.
There are four type of core components
◦ Activities
APPLICATION’S LIFE CYCLE ◦ Services
◦ Broadcast Receiver
◦ Content Provider
Occasionally hardware resources may become critically low and the OS could order early termination of
Background services Broadcast receiver Foreground activity Content provider User application
query any process. The decision considers factors such as:
◦ Number and age of the application’s components currently running,
Method() Local
◦ Relative importance of those components to the user, and
insert
Work to be done dataset
after receiving an
delete
◦ How much free memory is available in the system.
ORANGE message
Send an ORANGE signal Cloud
dataset
Waiting. My filter only update
accepts ORANGE signals.
Ignoring all others.
@Override
Activity n – 1 protected void onStop() {super.onStop(); …}
…
@Override
Activity 2 Removed to free resources protected void onDestroy() { super.onDestroy(); …}
}
Activity 1
COMPONENT’S LIFE CYCLE COMPONENT’S LIFE CYCLE COMPONENT’S LIFE CYCLE
(Activity states and callback (Activity state: running & paused & stopped) (Activity life cycle)
methods) Your activity is active or running when it is in foreground of screen (seating on top of the activity stack) Another view of activity life cycle
An activity has essentially three phases: This is the activity that has “focus” and its graphical interface is responsive to the user’s interactions.
◦ 1. It is active or running
◦ 2. It is paused or Your Activity is paused if it has lost focus but is still visible to the user.
◦ 3. It is stopped . That is, another activity seats on top and new activity either is transparent or doesn't cover full screen.
Moving from one state to the other is A paused activity is alive (maintaining its state information and attachment to the window manager).
accomplished by means of the callback methods Paused activities can be killed by the system when available memory becomes extremely low.
listed on the edges of the diagram
Your Activity is stopped if it is completely obscured by another activity.
Although stopped, it continues to retain all its state information.
It is no longer visible to the user ( its window is hidden, and its life cycle could be terminated at any point by the system if
the resources that it holds are needed elsewhere).
http://developer.android.com/training/basics/activity-lifecycle/starting.html
SharedPreference files are permanently stored in the application’s process space. </EditText>
6. You are asked to observe the sequence of messages displayed when the application: <Button android:id=“@+id/button1”
android:layout_width=“wrap_content”
Use file explorer to locate the entry: data/data/your-package-name/shared-prefs 6.1. Loads for the first time android:layout_height=“wrap_content”
6.2. Is paused after clicking HOME button android:text=“Exit” />
<TextView android:id=“@+id/textView1”
6.3. Is re-executed from launch-pad android:layout_width=“wrap_content”
6.4. Is terminated by pressing BACK and its own EXIT button android:layout_height=“wrap_content”
android:text=“spy box - try clicking HOME and BACK” />
6.5. Re-executed after a background color is set </LinearLayout>
EXAMPLE EXAMPLE EXAMPLE
(The LifeCycle app – code: MainActivity.java ) (The LifeCycle app – code: MainActivity.java ) (The LifeCycle app – code: MainActivity.java )
@Override @Override private void updateMeUsingSavedStateData() {
package csu.matos.lifecycle; //set GUI listeners, watchers,...
protected void onDestroy() { protected void onStart() { super.onStart();
import java.util.Locale; btnExit.setOnClickListener(new OnClickListener() { // (in case it exists) use saved data telling backg color
super.onDestroy(); //if appropriate, change background color to chosen value
. . . //other libraries omitted for brevity @Override SharedPreferences myPrefContainer = getSharedPreferences(PREFNAME, Activity.MODE_PRIVATE);
Toast.makeText(context, “onDestroy”, duration).show(); updateMeUsingSavedStateData();
public class MainActivity extends Activity { public void onClick(View v) { finish();}
} Toast.makeText(context, “onStart”, duration).show(); String key = “chosenBackgroundColor”;
//class variables });
@Override } String defaultValue = “white”;
private Context context; //observe (text) changes made to EditText box (color selection)
protected void onPause() { @Override if (( myPrefContainer != null ) && myPrefContainer.contains(key)){
private int duration = Toast.LENGTH_SHORT; txtColorSelected.addTextChangedListener(new TextWatcher() {
super.onPause(); protected void onStop() { super.onStop(); Toast.makeText(context, “onStop”, duration).show(); }
//PLUMBING: Pairing GUI controls with Java objects @Override String color = myPrefContainer.getString(key, defaultValue);
//save state data (background color) for future use private void setBackgroundColor(String chosenColor, LinearLayout myScreen) {
private Button btnExit; public void onTextChanged(CharSequence s, int start, int before, int count) { /* nothing TODO, needed by interface */ } setBackgroundColor(color, myScreen);
String chosenColor = txtSpyBox.getText().toString(); //hex color codes: 0xAARRGGBB AA:transp, RR red, GG green, BB blue
private EditText txtColorSelected; @Override }
saveStateData(chosenColor); if (chosenColor.contains(“red”)) myScreen.setBackgroundColor(0xffff0000); //Color.RED
private TextView txtSpyBox; public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* nothing TODO, needed by interface */ }
Toast.makeText(context, “onPause”, duration).show(); if (chosenColor.contains(“green”)) myScreen.setBackgroundColor(0xff00ff00); //Color.GREEN }//updateMeUsingSavedStateData
private LinearLayout myScreen; @Override
} if (chosenColor.contains(“blue”)) myScreen.setBackgroundColor(0xff0000ff); //Color.BLUE } //Activity
private String PREFNAME = “myPrefFile1”; public void afterTextChanged(Editable s) {
@Override if (chosenColor.contains(“white”)) myScreen.setBackgroundColor(0xffffffff); //Color.WHITE
@Override //set background to selected color
protected void onRestart() { } //setBackgroundColor
protected void onCreate(Bundle savedInstanceState) { String chosenColor = s.toString().toLowerCase(Locale.US);
super.onRestart(); private void saveStateData(String chosenColor) {
super.onCreate(savedInstanceState); txtSpyBox.setText(chosenColor);
Toast.makeText(context, “onRestart”, duration).show(); //this is a little <key,value> table permanently kept in memory
//display the main screen setBackgroundColor(chosenColor, myScreen);
} SharedPreferences myPrefContainer = getSharedPreferences(PREFNAME, Activity.MODE_PRIVATE);
setContentView(R.layout.activity_main); }
@Override //pair <key,value> to be stored represents our 'important' data
//wiring GUI controls and matching Java objects });
protected void onResume() { SharedPreferences.Editor myPrefEditor = myPrefContainer.edit();
txtColorSelected = (EditText)findViewById(R.id.editText1); //show the current state's name
super.onResume(); String key = “chosenBackgroundColor”, value = txtSpyBox.getText().toString();
btnExit = (Button) findViewById(R.id.button1); context = getApplicationContext();
Toast.makeText(context, “onResume”, duration).show(); myPrefEditor.putString(key, value);
txtSpyBox = (TextView)findViewById(R.id.textView1); Toast.makeText(context, "onCreate", duration).show();
} myPrefEditor.commit();
myScreen = (LinearLayout)findViewById(R.id.myScreen1); } //onCreate
}//saveStateData
EXAMPLE EXAMPLE
(The LifeCycle app – code: MainActivity.java ) (The LifeCycle app – code: MainActivity.java ) APPENDIX
User selects a green background and clicks the HOME key. When the app is paused the user’s selection is Using Bundles to save/restore State Values
saved, the app is still active, but it is not visible. @Override
public void onCreate(Bundle savedInstanceState) {
...
if ( savedInstanceState != null )
String someStrValue = savedInstanceState.getString(“STR_KEY”, “Default”);
...
}
@Override
public void onSaveInstanceState(Bundle outState) {
...
outState.putString(“STR_KEY”, “blah blah blah”);
super.onSaveInstanceState(myBundle);
...
}
Note: This approach works well when Android kills the app (like in a device-rotation event), however; it will not create
the state bundle when the user kills the app (eg. pressing BackButton). Hint: It is a better practice to save state using
SharedPreferences in the onPause( ) method.
APPENDIX APPENDIX
Use the onCreate method to initialize a control variable with the original device’s orientation. During onPause compare the current
The function below allows to obtain the current ORIENTATION of the device as NORTH(0), orientation with its original value; if they are not the same then the device was rotated.
WEST(1), SOUTH(2) and EAST(3). int originalOrientation; //used to detect orientation change
@Override
private int getOrientation(){ protected void onCreate(Bundle savedInstanceState) {
// the TOP of the device points to [0:North, 1:West, 2:South, 3:East] ...
Display display = ((WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); setContentView(R.layout.activity_main);
display.getRotation(); originalOrientation = getOrientation();
return display.getRotation(); ...
}
}
@Override
top North: 0 protected void onPause() {
super.onPause();
if( getOrientation() != originalOrientation ){
West: 1 East: 3 // Orientation changed - phone was rotated
// put a flag in outBundle, call onSaveInstanceState(…)
top top }else {
// no orientation change detected in the session
}
}
South: 2 top