In this lesson:

- Activity LifeCycle - Activity behavior during creation, invocation and closing

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

Theory

While application is running, we create new Activities and close old ones, hide the application and open it again and so on, and Activity can process all these events. It is required, for example, to free resources or to save data. It is described in detail in documentation.

Activity, created in a running application can be in one of three states

Resumed - Activity is visible on the screen, it is focused and the user can interact with it. This state is sometimes called Running
Paused - Activity is not focused, user cannot interact with it, but it is visible (it is covered by another Activity, which doesn’t cover the whole screen or is transparent)
Stopped - Activity is not visible (is completely covered by another Activity), that is, it is not focused and user cannot interact with it

When Activity goes from one state to another, the system invokes its different methods, which we can fill in with our code. This can be illustrated as a diagram:

To simplify understanding I’ve given a brief state description in brackets below the state names. Cross means that Activity does not exist.

So we have the following methods that are invoked by the system:

onCreate() - invoked when Activity is created for the first time
onStart() - invoked before Activity is shown to the user
onResume() - invoked before Activity becomes available for user interaction

onPause() - invoked before another Activity is shown
onStop() - invoked when Activity is not visible to the user
onDestroy() - invoked before Activity is destroyed

That is, these methods do NOT cause state changes. But vice-versa, state change of an Activity is a trigger which invokes these methods. We are informed about state changes in this way, so we can react accordingly. Let’s see in which order are these methods invoked in practice.

 

Practice

In this lesson we will have to emulate screen orientation changes. But Android emulator 2.3 does it wrong, so we will use 2.2 version in this project. To do so, we need to create a new AVD version 2.2 

 

Let’s create a project (Note that we use Android 2.2 version):

Project name: P0231_OneActivityState
Build Target: Android 2.2
Application name: OneActivityState
Package name: ru.startandroid.develop.p0231oneactivitystate
Create Activity: MainActivity

Do not change the layout. It is not important for now. Open MainActivity.java. There is some code by default as usual:

package ru.startandroid.develop.p0231oneactivitystate;

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

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

We can see, that already familiar for us onCreate method is already implemented. I will repeat once again, it is important to understand that this method does NOT create an Activity. Creation is the system business. That is, the system creates an Activity and gives us an opportunity to participate in it and run our own code inside onCreate() method. We use this opportunity and tell the system that Activity should display the screen from R.layout.main.

Let’s add all the remaining methods from the diagram and add log entry to each of them.

package ru.startandroid.develop.p0231oneactivitystate;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
  
  final String TAG = "States";
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d(TAG, "MainActivity: onCreate()");
    }
    
  @Override
  protected void onStart() {
    super.onStart();
    Log.d(TAG, "MainActivity: onStart()");
  }

  @Override
  protected void onResume() {
    super.onResume();
    Log.d(TAG, "MainActivity: onResume()");
  }

  @Override
  protected void onPause() {
    super.onPause();
    Log.d(TAG, "MainActivity: onPause()");
  }

  @Override
  protected void onStop() {
    super.onStop();
    Log.d(TAG, "MainActivity: onStop()");
  }
    
  @Override
  protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "MainActivity: onDestroy()");
  }
}

While implementing these methods always invoke the corresponding superclass methods and always before your code. See the code above. Each method contains superclass method invocation and our own code is located after it. 

Now, when the methods will be invoked we will see it in logs. Configure filter for the "States" tag, to not look for your messages in the pile of other logs. We’ve learnt how it is done in the lesson 12

Save everything and run the application. After running see the log:

MainActivity: onCreate()
MainActivity: onStart()
MainActivity: onResume()

Activity has been created, passed two states (Stopped, Paused) and now is in the third state - Resumed. It means it was created (onCreate), displayed (onStart) and gained the ability to interact with the user (onResume).

Now press the Back button in the emulators. Activity has closed. See the log:

MainActivity: onPause()
MainActivity: onStop()
MainActivity: onDestroy()

Activity does the opposite to its creation. At first, the focus is lost (onPause ), than it disappears from the screen (onStop), then destroyed completely (onDestroy).

 

Screen orientation change

Let’s see how will Activity behave when we change our screen orientation. Run the application again (or find it in the list of running applications on the emulator or press CTRL + F11 in Eclipse). Three methods that were invoked on creation are displayed. Now press CTRL + F12 in the emulator, the orientation has changed. It looks like nothing special has happened, but have a look at the logs and see:

MainActivity: onPause()
MainActivity: onStop()
MainActivity: onDestroy()
MainActivity: onCreate()
MainActivity: onStart()
MainActivity: onResume()

Activity is completely destroyed and created again. During this process, procedures of saving and restoring data usually occur, not to lose data and for application to save its appearance. We will talk in the next lessons about how it is done.

There is also onRestart method. It is invoked before onStart if Activity is not created from scratch but is restored from the Stopped state. We will have look at this method in the next lesson.

 

Usually in books this topic is presented a little bit different. But as for me, this template explanation seems not very clear, that’s why I’ve written my own. As usual, I hope that I’ve managed to explain the subject well )

My advice for you is, after this lesson - to read documentation, link to which I’ve provided in the beginning of the lesson. Everything is written very well there. And you will remember everything better. But for now, the most important thing is to understand in which moment each method is invoked. And later we will look through how we can use it and what to code there.

 

In the next lesson we will:

- learn state changes by example with two Activities


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language