Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1
Exploring the activity lifecycle by example

61

When you pressed the Back button, you told Android, “I’m done with this activity, and I won’t need
it anymore.” Android then destroyed your activity’s view and removed all traces of the activity from
memory. This is Android’s way of being frugal with your device’s limited resources.


Launch GeoQuiz again by clicking the GeoQuiz app icon. Android creates a new instance of
QuizActivity from scratch and calls onCreate(), onStart(), and onResume() to move QuizActivity
from nonexistent to resumed.


Now press the Home button. The home screen displays and QuizActivity moves completely out of
view. What state is QuizActivity in now? Check Logcat for a hint. Your activity received calls to
onPause() and onStop(), but not onDestroy() (Figure 3.6).


Figure 3.6  Pressing the Home button stops the activity


Pressing the Home button means the user is telling Android, “I’m going to go look at something
else, but I might come back. I’m not really done with this screen yet.” Android pauses and ultimately
stops your activity. This means, after pressing Home, your instance of QuizActivity hangs out in the
stopped state (in memory, not visible, and not active in the foreground). Android does this so it can
quickly and easily restart QuizActivity where you left off when you come back to GeoQuiz later.


(This is not the whole story about going Home. Stopped activities can be destroyed at the discretion of
the OS. See the section called The Activity Lifecycle, Revisited for the rest of the story.)


Go back to GeoQuiz by selecting the GeoQuiz task card from the overview screen. To do this, press the
Recents button next to the Home button (Figure 3.7). (On devices without a Recents button, long-press
the Home button.)


Figure 3.7  Back, Home, and Recents buttons


http://www.ebook3000.com

Free download pdf