Recipe Utilizing Other Lifecycle Functions

The following recipe provides a simple way to see the activity lifecycle in action. For illustration purposes, each overridden function is explicit and a Toast command is added to show on screen when the function is entered (more detail on the Toast widget is provided in Chapter 3).The activity is shown in Listing 2.6. Run it on an Android device and try various cases. In particular, note the following:

■ Changing the screen orientation destroys and recreates the activity from scratch.

■ Pressing the Home button pauses the activity, but does not destroy it.

■ Pressing the Application icon might start a new instance of the activity, even if the old one was not destroyed.

■ Letting the screen sleep pauses the activity and the screen awakening resumes it. (This is similar to taking an incoming phone call.)

Listing 2.6 src/com/cookbook/activityJifecycle/ActivityLifecyclejava package com.cookbook.activity_lifecycle;

import android.app.Activity; import android.os.Bundle; import android.widget.Toast;

public class ActivityLifecycle extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();

@Override protected void onStart() { super.onStart();

Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();

@Override protected void onResume() { super.onResume();

Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();

@Override protected void onRestart() { super.onRestart();

Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();

@Override protected void onPause() Toast.makeText(this, super.onPause();

@Override protected void onStop() {

Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show(); super.onStop();

@Override protected void onDestroy() {

Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show(); super.onDestroy();

As seen here, various common actions by the user can cause the activity to be paused, killed, or even launch multiple versions of the application. Before moving on, it is worth mentioning two additional simple recipes that can control this behavior.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment