Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Logging the Activity Lifecycle


57

Logging the Activity Lifecycle


In this section, you are going to override lifecycle methods to eavesdrop on QuizActivity’s lifecycle.
Each implementation will simply log a message informing you that the method has been called. This
will help you see how QuizActivity’s state changes at runtime in relation to what the user is doing.


Making log messages


In Android, the android.util.Log class sends log messages to a shared system-level log. Log has
several methods for logging messages. Here is the one that you will use most often in this book:


public static int d(String tag, String msg)


The d stands for “debug” and refers to the level of the log message. (There is more about the Log levels
in the final section of this chapter.) The first parameter identifies the source of the message, and the
second is the contents of the message.


The first string is typically a TAG constant with the class name as its value. This makes it easy to
determine the source of a particular message.


Open QuizActivity.java and add a TAG constant to QuizActivity:


Listing 3.1  Adding a TAG constant (QuizActivity.java)


public class QuizActivity extends AppCompatActivity {


private static final String TAG = "QuizActivity";
...
}


Next, in onCreate(Bundle), call Log.d(...) to log a message.


Listing 3.2  Adding a log statement to onCreate(Bundle)
(QuizActivity.java)


public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
...
}
}


http://www.ebook3000.com

Free download pdf