Android lifecycle callbacks

 

Implementing The Lifecycle Callbacks

When an activity transitions into and out of the different states, it is notified through various callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes. The following skeleton activity includes each of the fundamental lifecycle methods:

If you would like to Enrich your career with an Android certified professional, then visit Mindmajix - A Global online training platform:“Android training”Course.This course will help you to achieve excellence in this domain.

public class ExampleActivity extends Activity { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() { super.onStart();
// The activity is about to become visible.
}
rotected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed")
}
protected void onPause() { super.onPause();
//  Another activity is taking focus (this activity is about to be "paused"). } protected void onStop() {
super.onStop();
//  The activity is no longer visible (it is now "stopped")
}
protected void onDestroy() { super.onDestroy();
// The activity is about to be destroyed.
}}

By implementing these methods, you can monitor three nested loops in the activity lifecycle:

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of “global” state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread in onDestroy()
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain the resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.
  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

The rectangles represent the callback methods you can implement to perform operations when the activity transitions between states.
 Activity life cycle

Saving activity state

When an activity is paused or stopped, the state of the activity is retained. Activity object is still held in memory when it is paused or stopped—all information about its members and the current state is still alive. Thus, any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it “resumes”), those changes are still there.
Saving activity 

The two ways in which an activity returns to user focus with its state intact: either the activity is stopped, then resumed and the activity state remains intact (left), or the activity is destroyed, then recreated and the activity must restore the previous activity state (right).
The callback method in which you can save information about the current state of your activity is onSaveInstanceState(). The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object. The Bundle is where you can store state information about the activity as name-value pairs, using methods such as putString(). Then, if the system kills your activity’s process and the user navigates back to your activity, the system passes the Bundle to onCreate(), so you can restore the activity state you saved during onSaveInstanceState(). If there is no state information to restore, then the Bundle passed to onCreate() is null

Frequently Asked Android Interview Questions & Answers

Note: There’s no guarantee that onSaveInstanceState() will be called before your activity is destroyed because there are cases in which it won’t be necessary to save the state (such as when the user leaves your activity using the BACK key, because the user is explicitly closing the activity). If the method is called, it is always called before onStop() and possibly before onPause().
You can also explicitly stop a view in your layout from saving its state by setting the android: save enabled attribute to” false”or by calling the setSaveEnabled() method. Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently.
Because the default implementation of onSaveInstanceState() helps save the state of the UI, if you override the method in order to save additional state information, you should always call the superclass implementation of onSaveInstanceState() before doing any work.

Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.

MindMajix Youtube Channel

Handling configuration changes

Some device configurations can change during run time (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed immediately by onCreate()). The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you’ve provided. If you design your activity to properly handle this event, it will be more resilient to unexpected events in the activity lifecycle.
The best way to handle a configuration change, such as a change in the screen orientation, is to simply preserve the state of your application using onSaveInstanceState() and onRestoreInstanceState() (or onCreate()).

Checkout:-Background Services In Android

Coordinating activities
When one activity starts another, they both experience lifecycle transitions. The first activity pauses and stops (though, it won’t stop if it’s still visible in the background), while the other activity is created. In case these activities share data saved to disc or elsewhere, it’s important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.
The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here’s the order of operations that occur when Activity A starts Acivity B:

  1. Activity A’s onPause() method executes.
  2. Activity B’s onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. Then, if Activity A is no longer visible on the screen, it's   onStop() method executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example, if you have to write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of during onStop().

Explore Android Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Android TrainingNov 19 to Dec 04View Details
Android TrainingNov 23 to Dec 08View Details
Android TrainingNov 26 to Dec 11View Details
Android TrainingNov 30 to Dec 15View Details
Last updated: 03 Apr 2023
About Author

Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.

read less