Stages of the Activity lifecycle | Android Developers

3. Explore the lifecycle methods and add basic logging

Every activity has what is known as a lifecycle. This term is an allusion to plant and animal lifecycles, like the lifecycle of a butterfly — the different states of the butterfly show its growth from egg to caterpillar to pupa to butterfly to death .

Butterfly Lifecycle - growth from egg to caterpillar to pupa to butterfly to death.

Similarly, the activity lifecycle consists of the different states that an activity can go through, from when the activity first initializes to its destruction, at which time the operating system (OS) reclaims its memory. Typically, the entry point of a program is the main() method. Android activities, however, begin with the onCreate() method; this method would be the equivalent of the egg stage in the above example. You have used activities already, many times throughout this course, and you might recognize the onCreate() method. As the user starts your app, navigates between activities, navigates inside and outside of your app, the activity changes state.

The following diagram shows all the activity lifecycle states. As their names indicate, these states represent the status of the activity. Notice that, unlike the butterfly lifecycle, an activity can go back and forth between states throughout the lifecycle, instead of only moving in a single direction.

Note: An Android app can have multiple activities. However, it is recommended to have a single activity, and so far that is what you have been implementing in this course.

ca808edb1c95f07a.png

Often, you want to change some behavior, or run some code, when the activity lifecycle state changes. Therefore, the Activity class itself, and any subclasses of Activity such as ComponentActivity, implement a set of lifecycle callback methods. Android invokes these callbacks when the activity moves from one state to another, and you can override those methods in your own activities to perform tasks in response to those lifecycle state changes. The following diagram shows the lifecycle states along with the available overridable callbacks.

The Activity Lifecycle scheme

Note: The asterisk on the onRestart() method indicates that this method is not called every time the state transitions between Created and Started. It is only called if onStop() was called and the activity is subsequently restarted.

It’s important to know when Android invokes the overridable callbacks and what to do in each callback method, but both of these diagrams are complex and can be confusing. In this codelab, instead of just reading what each state and callback means, you’re going to do some detective work and build your understanding of the Android activity lifecycle .

Step 1: Examine the onCreate() method and add logging

To figure out what’s going on with the Android lifecycle, it’s helpful to know when the various lifecycle methods are called. This information helps you identify where things are going wrong in the Dessert Clicker app .
A simple way to determine this information is to use the Android logging functionality. Logging enables you to write short messages to a console while the app runs and use it to see when different callbacks are triggered .

  1. Run the Dessert Clicker app and tap several times on the picture of the dessert. Note how the value for Desserts sold and the total dollar amount changes.
  2. Open MainActivity.kt and examine the onCreate() method for this activity:
override fun onCreate(savedInstanceState: Bundle?) {
    // ...
}

In the activity lifecycle diagram, you may recognize the onCreate() method, because you’ve used this callback before. It’s the one method that every activity must implement. The onCreate() method is where you should do any one-time initializations for your activity. For example, in onCreate(), you call setContent(), which specifies the activity’s UI layout.

The onCreate Lifecycle method

The onCreate() lifecycle method is called once, just after the activity initializes—when the OS creates the new Activity object in memory. After onCreate() executes, the activity is considered created.

Note: When you override the onCreate() method, you must call the superclass implementation to complete the creation of the Activity, so within it, you must immediately call super.onCreate(). The same is true for other lifecycle callback methods.

  1. Add the following constant at the top level of the MainActivity.kt, above the class declaration class MainActivity.

A good convention is to declare a TAG constant in your file as its value will not change.

To mark it as a compile-time constant, use const when declaring the variable. A compile-time constant is a value that is known during compilation.

private const val TAG = "MainActivity"
  1. In the onCreate() method, just after the call to super.onCreate(), add the following line:
Log.d(TAG, "onCreate Called")
  1. Import the Log class, if necessary (press Alt+Enter, or Option+Enter on a Mac, and select Import.) If you enabled auto imports, this should happen automatically.
import android.util.Log

The Log class writes messages to the Logcat. The Logcat is the console for logging messages. Messages from Android about your app appear here, including the messages you explicitly send to the log with the Log.d() method or other Log class methods.

There are three important aspects of the Log instruction:

  • The priority of the log message, that is, how important the message is. In this case, the Log.v() logs verbose messages. Log.d() method writes a debug message. Other methods in the Log class include Log.i() for informational messages, Log.w() for warnings, and Log.e() for error messages.
  • The log tag (the first parameter), in this case "MainActivity". The tag is a string that lets you more easily find your log messages in the Logcat. The tag is typically the name of the class.
  • The actual log message, called msg (the second parameter), is a short string, which in this case is "onCreate Called".

a4ff4aa74384ff6.png

  1. Compile and run the Dessert Clicker app. You don’t see any behavior differences in the app when you tap the dessert. In Android Studio, at the bottom of the screen, click the Logcat tab.

ed03d4bb1f020995.png

  1. In the Logcat window, type tag:MainActivity into the search field.

8da9e2a7c0656939.png

The Logcat can contain many messages, most of which aren’t useful to you. You can filter the Logcat entries in many ways, but searching is the easiest. Because you used MainActivity as the log tag in your code, you can use that tag to filter the log. Your log message includes the date and time, your log tag, the name of the package (com.example.dessertclicker), and the actual message. Because this message appears in the log, you know that onCreate()was executed.

Step 2: Implement the onStart() method

The onStart() lifecycle method is called just after onCreate(). After onStart() runs, your activity is visible on the screen. Unlike onCreate(), which is called only once to initialize your activity, onStart()can be called by the system many times in the lifecycle of your activity.

a357d2291de472d9.png

Note that onStart()is paired with a corresponding onStop()lifecycle method. If the user starts your app and then returns to the device’s home screen, the activity is stopped and is no longer visible on screen.

  1. In Android Studio, with MainActivity.kt open and the cursor within the MainActivity class, select Code > Override Methods… or press Control+O. A dialog appears with a long list of all the methods you can override in this class.

11ff93bee1c3940f.png

  1. Start entering onStart to search for the correct method. To scroll to the next matching item, use the down arrow. Choose onStart()from the list and click OK to insert the boilerplate override code. The code looks like the following example:
override fun onStart() {
    super.onStart()
}
  1. Inside the onStart()method, add a log message:
override fun onStart() {
    super.onStart()
    Log.d(TAG, "onStart Called")
}
  1. Compile and run the Dessert Clicker app and open the Logcat pane.
  2. Type tag:MainActivity into the search field to filter the log. Notice that both the onCreate()and onStart()methods were called one after the other, and that your activity is visible on screen.
  3. Press the Home button on the device and then use the Recents screen to return to the activity. Notice that the activity resumes where it left off, with all the same values, and that onStart() is logged a second time to Logcat. Notice also that the onCreate() method is not called again.
2023-04-11 11:23:38.116  3275-3275  MainActivity            com.example.dessertclicker           D  onCreate Called
2023-04-11 11:23:38.161  3275-3275  MainActivity            com.example.dessertclicker           D  onStart Called
2023-04-11 11:24:16.721  3275-3275  MainActivity            com.example.dessertclicker           D  onStart Called

Note: As you experiment with your device and observe the lifecycle callbacks, you might notice unusual behavior when you rotate your device. You’ll learn about that behavior later in this codelab.

Step 3: Add more log statements

In this step, you implement logging for all the other lifecycle methods .

  1. Override the remainder of the lifecycle methods in your MainActivity and add log statements for each one, as shown in the following code:
override fun onResume() {
    super.onResume()
    Log.d(TAG, "onResume Called")
}

override fun onRestart() {
    super.onRestart()
    Log.d(TAG, "onRestart Called")
}

override fun onPause() {
    super.onPause()
    Log.d(TAG, "onPause Called")
}

override fun onStop() {
    super.onStop()
    Log.d(TAG, "onStop Called")
}

override fun onDestroy() {
    super.onDestroy()
    Log.d(TAG, "onDestroy Called")
}
  1. Compile and run Dessert Clicker again and examine Logcat.

Notice that this time, in addition to onCreate() and onStart(), there’s a log message for the onResume() lifecycle callback.

2023-04-11 11:28:21.145  4244-4244  MainActivity            com.example.dessertclicker           D  onCreate Called
2023-04-11 11:28:21.187  4244-4244  MainActivity            com.example.dessertclicker           D  onStart Called
2023-04-11 11:28:21.189  4244-4244  MainActivity            com.example.dessertclicker           D  onResume Called

When an activity starts from the beginning, you see all three of these lifecycle callbacks called in order :

  • onCreate() when the system creates the app.
  • onStart() makes the app visible on the screen, but the user is not yet able to interact with it.
  • onResume() brings the app to the foreground, and the user is now able to interact with it.

Despite the name, the onResume() method is called at startup, even if there is nothing to resume.

The Activity Lifecycle scheme

Stages of the Activity lifecycle | Android Developers

Bài viết liên quan
Hotline 24/7: O984.666.352
Alternate Text Gọi ngay