Sunday, June 26, 2022

Activity Lifecycle in Android Studio

In the previous articles we learned the activities in android studio. Also, we mentioned that the android app experience differs from its desktop one. This difference in that the android app doesn’t always begin in the same place. Moreover there is no a determined start for the android app. For that, in this article you will learn the concept of activity lifecycle in android studio.

As a user navigates through, out of, and back to your app, instances of an activity in your app changes through different states in their lifecycle. Moreover, we can determine that the android system is creating, stopping, resuming an activity or destroying all the process through a number of callback methods provided by the activity class.

Good Implementation of the Lifecycle Callback Methods

By using lifecycle callback methods, you can determine how your activity behaves when the user leaves and re-enters the activity. For example, when you build a streaming video player app, you need to pause the video and terminate the network connection when the user switches to another app. So that, a good implementation of the lifecycle call back methods:

  • allows you to perform specific work that’s appropriate to a given change of state. 
  • Doing the right work at the right time and handling transitions properly make your app more robust and performant.

Also, your app will avoid:

  • Crashing if the user receives a phone call or switches to another app while using your app.
  • Consuming valuable system resources when the user is not actively using it.
  • Losing the user’s progress if they leave your app and return to it at a later time.
  • Crashing or losing the user’s progress when the screen rotates between landscape and portrait orientation.

Activity Lifecycle Callback

There is a core set of six callback that contribute in the transitions between stages of the activity lifecycle.

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onDestroy()

The system invokes each of these callbacks as an activity enters a new state.

activity lifecycle

In order to understand the above illustration of activity life cycle you need to try it practically. So that, lets start a new android studio project. After successful creation of a new project, copy the following code and past it in the main activity java class (override the exiting code).

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivityCallBacks";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: "+"The onCreate method callback");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: "+"The onStart method callback");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: "+"The onResume method callback");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: "+"The onPause method callback");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: "+"The onStop method callback");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: "+"The onDestroy method callback");
    }
    
}

The code in Kotlin:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d(TAG, "onCreate: " + "The onCreate method callback")
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart: " + "The onStart method callback")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: " + "The onResume method callback")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause: " + "The onPause method callback")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop: " + "The onStop method callback")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: " + "The onDestroy method callback")
    }

    companion object {
        private const val TAG = "MainActivityCallBacks"
    }

The main activity class inherits the AppCompatActivity so that, you can override the life cycle callback methods. In each method I added Log.d for showing which method has been called in each state of the app. Now, run your app and then open the LogCat from the bottom part of window toolbar. In the LogCat search type “MainActivityCallBacks” to show the call methods which invoked in the first activity creation.

activity life cycle callback method

From the above image you will note that the first activity creation, the onCreate() method has invoked then onStart(), finally onResume(). Now try to click on the home button in your emulator or device. You will see two callback methods had added to the logcat onPause() and onStop().

activity life cyclehome button click

If you return to the app, you will see that the methods onStart() and onResume() have been invoked.

Well done, now lets talk about every method that has been invoked in the activity life cycle:

onCreate() Method Callback

This method fires when the app creates the activity and we must use this method. Also, you will need to add the basic application startup logic that should happen only once through the activity life cycle. For example, binding data, or associating the view model. This method receives the parameter “savedInstanceState“, which is a Bundle object containing the activity’s previously saved state. If the activity has never existed before, the value of the Bundle object is null.

The activity doesn’t persist in the on_Create state, so after the execution of the on_create method the system fires the omStart() and onResum() methods.

onStart() Method Callback

On Start method invoked when the activity enters the on start state. The method call make the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI. This method executed quickly and after the the activity enters the on resume state.

onResume() Method Callback

This method invoked when the activity enters the resume state where the app ready to interact with the user in the foreground. The app stays in this state until something happens to take focus away from the app. Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device screen’s turning off.

When an interruptive event occurs, the activity enters the Paused state, and the system invokes the onPause() callback.

If the activity returns to the Resumed state from the Paused state, the system once again calls onResume() method. For this reason, you should implement onResume() to initialize components that you release during onPause(), and perform any other initializations that must occur each time the activity enters the Resumed state.

onPause() Method Callback

When the user inters the multi-window mode (clicks on task button) this method invoked by the system. Moreover, it indicates that the user is leaving your activity. Further more, you can use this method to to pause or adjust operations that should not continue while the activity is in the Paused state and that you expect to resume shortly.

There are several reasons why an activity may enter this state. For example:

  • Some event interrupts app execution, as described in the onResume() section. This is the most common case.
  • In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode. Because only one of the apps (windows) has focus at any time, the system pauses all of the other apps.
  • A new, semi-transparent activity (such as a dialog) opens. As long as the activity is still partially visible but not in focus, it remains paused.

Completion of the onPause() function does not indicate that the operation leaves the Pause condition. Instead the operation persists in that state until either the activity returns or becomes completely inaccessible to the user.

If the activity resumes, the system once again invokes the onResume() callback. If the activity returns from the Paused state to the Resumed state, the system keeps the Activity instance resident in memory, recalling that instance when the system invokes onResume(). In this case, you don’t need to re-initialize the components that were generated during any of the callback methods leading to the Revived state.

If the activity becomes completely invisible, the system calls onStop(). The next section discusses the onStop() callback.

onStop() Method Callback

When your activity is no longer accessible to the user, the Stop state is reached and the device invokes a callback onStop(). This will occur, for example, where the newly released activity fills the whole screen. The system can even call onStop() when the operation finishes and is about to be terminated. You can also use onStop() to run comparatively CPU intensive shutdown operations. For eg, if you can’t find a more timely time to save information to a database, you may be able to do so when onStop ().

From the Stopped state, the activity either resumes communicating with the user, or the activity ends up running and goes out. If the operation returns, the machine will invoke Restart (). If the operation is over, the machine will call onDestroy() method.

onDestroy() Method Callback

This is called before the activity is destroyed. 

The system invokes this callback either because:

  1. the activity is finishing (due to the user completely dismissing the activity or due to finish() being called on the activity), or
  2. the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)

If the activity is finishing, onDestroy() is the final lifecycle callback the activity receives. If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls onCreate() on that new instance in the new configuration.

The onDestroy() callback should release all resources that have not yet been released by earlier callbacks such as onStop().


Read more about activities and activity life cycle

Thank You

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

KU NUR RASYIDAH BINTI KU BIDE on Custom Calendar View Android | Project Java Files
SHIVANT KUMAR PANDEY on Login And Registration by Firebase
Adriane Troy U. Alariao on Custom Calendar View With Events Android