What does the Android activity life cycle do?

Source: Internet
Author: User

The Android system calls the corresponding callback function to execute the code according to the different stages of the life cycle. The system has an ordered set of callback functions to start and destroy an activity. This section discusses what to do and what not to do in the callback functions for different life cycles.

Understanding the callback of the life cycle

In the life cycle of an activity, the system invokes a series of life-cycle callback functions like a pyramid model. Each stage of the activity's life cycle is like a step in a pyramid. When the system creates a new activity instance, each callback function moves the activity state one step up. Being at the top of the pyramid means that the current activity is in the foreground and in a state where the user can interact with it.

When the user exits the activity, in order to reclaim the activity, the system calls other methods to move the activity state down one step. In some cases, the activity is hidden under the pyramid to wait (for example, when the user switches to another app), where the activity can go back to the top (if the user returns to the activity) and restore the user's state when they leave.

This is a life cycle diagram of activity, and of course we can also see the callback method for the entire activity lifecycle call from the print. The following print is from start one mainactivity jump to another otheractivity, and then click Back until the entire program exits. Print as follows:

Depending on the complexity of the activity, it may not be necessary to implement all life cycle methods. But it is necessary to understand the timing of each method's callback and populate it with the appropriate functionality, making sure that the app executes as the user expects it to. How to achieve a user-desired app, we need to pay attention to the following points:

    • When using the app, the program is not crash because of calls or switching to other apps.
    • Users do not consume valuable system resources when they do not activate a component.
    • Leave the app and return after a period of time without losing the user's usage progress.
    • The screen rotation of the device does not crash or lose the user's use progress.

However, only three of these states are static, and the activity can exist for a longer period of time in these three states. (A few other states will soon switch off, the time to stay is relatively short)

    • Resumed: In this state, the activity is in the foreground and the user can interact with it. (often also understood as "running" state)
    • Paused: In this state, the activity part is obscured by another activity: the other activity comes to the foreground, but the translucent one does not cover the entire screen. The suspended activity no longer accepts the user's input and no longer executes any code.
    • Stopped: In this state, the activity is completely hidden and not visible to the user. Can be thought of in the background. When stopped, the activity instance and all of its state information (such as member variables, etc.) are preserved, but the activity cannot execute any code.
      Other states (created and started) are ephemeral, and the system quickly executes those callback functions and moves to the next state by performing the next phase of the callback function. That is, after the system calls OnCreate (), the OnStart () is immediately called, and then the Onresume () is executed quickly. The above is the basic activity life cycle.

Once the oncreate operation is complete, the system quickly calls the OnStart () and Onresume () methods. Our activity will not stay in the created or started state. Technically, the activity begins to be visible to the user after OnStart () is called, but Onresume () is executed quickly so that the activity stays in the resumed state until some factors change to change the state. For example, a call is received, the user switches to another activity, or the device screen shuts down.

Suspend and resume activity

When the app is used normally, the activity on the front end is sometimes blocked by other visible components (obstructed), which causes the current activity to enter the pause state. For example, when you open a translucent activity (for example, in the form of a dialog box), the previous activity is paused. As long as the previous activity is still partially visible, the activity will remain in the paused state.

However, once the previous activity is completely blocked and not visible, it goes into the stop state (discussed in the next section).

Once the activity enters the paused state, the system invokes the OnPause () method in activity, which can stop actions that should not be performed during the pause, such as pausing video playback, or saving information that might require long-term preservation. If the user returns to the current activity from the paused state, the system should restore the data and execute the Onresume () method.

Note: When our activity receives a signal to call OnPause (), that may mean that the activity will be suspended for a period of time, and the user is likely to return to our activity. However, that is also the first signal that users want to leave our activtiy.

Figure 1. When a translucent activity blocks activity, the system calls the OnPause () method and the activity stays in the paused state (1). If the user returns to the activity while the activity is still in the paused state, the system calls its Onresume () (2).

Suspend activity

When the system invokes OnPause () in activity, technically, it means that the activity is still partially visible. But more often it means that the user is leaving the activity and will immediately enter stopped state. You should usually do the following in the OnPause () callback method:

    • Stopping animations or other running operations can lead to a waste of CPU.
    • Submit content that is expected to be saved when the user leaves (such as a draft of a message).
    • Frees system resources, such as broadcast receivers, sensors (such as GPS), or any other resource that can affect power.

For example, if a program uses Camera,onpause () it is a good place to do things that release resources.

@OverridepublicvoidonPause() {    super.onPause();  // Always call the superclass method first    // Release the Camera because we don‘t need it when paused    // and other activities might need to use it.    ifnull) {        mCamera.release()        null;    }}

In general, OnPause () should not be used to save user-changed data (for example, by filling in a table of personal information) to permanent storage (file or DB). Only when you are sure that users expect those changes to be saved automatically (for example, by writing a draft of a message), store those data in permanent storage. However, we should avoid doing cpu-intensive work at OnPause (), such as writing data to DB, because it will cause the switch to the next activity to become slow (should put those heavy-load's work into OnStop ().

If the activity is actually to be stop, then we should reduce the amount of work in the OnPause () method in order to switch smoothly.

Note: When activity is paused, activity.html "target=" _blank ">activity instance resides in memory and is recalled when activity resumes. We do not need to reinitialize the component in a series of callback methods that revert to the resumed state.

Resume Activity

When the user resumes activity from the paused state, the system calls the Onresume () method.

Note that every time the system calls this method, the activity is in the foreground, including the first time it is created. Therefore, you should implement Onresume () to initialize those components that are released within the OnPause method and perform the initialization actions that the activity requires each time it enters the resumed state (such as starting animations and initializing components that are only needed when the user focus is acquired)

The following example of Onresume () corresponds to the above example of the OnPause ().

@OverridepublicvoidonResume() {    super.onResume();  // Always call the superclass method first    // Get the Camera instance as the activity achieves full user focus    ifnull) {        // Local method to handle camera init    }}
Stop and restart activity

It is important to properly stop and restart our activity, and in the activity lifecycle, they can ensure that the user perceives that the program exists without losing their progress. In the following key scenarios, stop and restart are involved:

    • Our app is stopped when the user opens the most recently used app menu and switches from our app to another app. If the user returns to our app via the launcher icon on the main screen of the phone or the Recently Used program window, our activity will restart.
    • The user initiates a new activity in our app, and the current activity will stop after the second activity is created. If--the user clicks the Back button, the first activtiy will be restarted.
    • Users receive a call call when they use our app.

The activity class provides the Activity.onstop () ">onstop () and Activity.onrestart ()" >onrestart () methods to allow calls to be made when activity stops and restarts. Unlike a partially blocked UI in a paused state, the stop State is that the UI is no longer visible and the user's focus shifts to another activity.

Note: Because the system saves instances of activity in memory when the activity is stopped, it is sometimes not necessary to implement OnStop (), Onrestart () or even the OnStart () method. Because most of the activity is relatively simple, the activity stops and restarts itself, we only need to use OnPause () to stop the running action and disconnect the system resource link.

Figure 1. Display: When the user leaves our activity, the system calls OnStop () to stop the activity (1). At this point, if the user returns, the system calls Onrestart () (2) and then quickly calls OnStart () (3) with Onresume () (4). Note: The system will always call the OnPause () method before OnStop (), regardless of the cause of activity stopping.

Stop activity

When activity calls the OnStop () method, activity is no longer visible, and all resources that are no longer needed should be freed. Once the activity is stopped, the system destroys its instance (associated with the stack structure, which usually causes the previous activity to be destroyed) when the memory space is needed. In extreme cases, the system directly kills our app process and does not execute the activity's OnDestroy () callback method, so we need to use OnStop () to free up resources, thus avoiding memory leaks. (This requires attention)

Although the OnPause () method is called before OnStop (), we should use OnStop () to perform shut-down operations on those CPU intensive, such as writing information to the database.

For example, here is an example of saving a draft of a note to persistent storage in the OnStop () method:

@Overrideprotected void OnStop () {super.onstop (); AlwaysCall   The superclass method  First//Save the Note'sdraft, because the activity is St    Opping//And we want to is sure the current note progress isn 't lost. Contentvalues Values = new Contentvalues ();    Values.put (NotePad.Notes.COLUMN_NAME_NOTE, Getcurrentnotetext ());    Values.put (NotePad.Notes.COLUMN_NAME_TITLE, Getcurrentnotetitle ()); Getcontentresolver (). Update(MUri,//The URI  for the note  to update. values,//The map  of column names  and new values  to a            Pply  to them.            null,// No SELECT criteria  is used.            null // No WHERE columns  is used. );}

After the activity has stopped, the activity object is saved in memory and recalled during activity resume. We do not need to reinitialize those components that are stored in memory before reverting to the resumed state. The system also saves the current state of each view in the layout, and if the user enters text in the EditText component, it is saved and therefore does not need to be saved and restored.

Note: Even if the activity is stopped at activity stop, it will still save the state of the View object (such as the text in EditText) into a bundle and restore them when the user returns to the activity ( The next section describes how to use bundles to hold other data when the activity is destroyed and re-established.

Start and restart activity

When activity returns to the foreground from the stopped state, it calls Onrestart (). The system calls the OnStart () method again, and the OnStart () method is called each time the activity is visible. The Onrestart () method is called only when the activity is resumed from the stopped state, so we can use it to perform some special recovery (restoration) work, and notice that it was previously stopped rather than destrory.

It is less common to use Onrestart () to restore activity state, so there is no guidelines for how this method is used. However, since the OnStop () method should do the cleanup of all activity resources, we need to re-instantiate those resources when we restart activtiy, and we also need to instantiate those resources when the activity is first created. In the above reason, you should use OnStart () as the corresponding method for OnStop (). OnStart () is called when the activity is created and the activity is restarted from the stop state. That is, what we do in the onstop, it should be in the onstart to re-create the deleted resources.

For example, because the user is likely to have a long time before returning to the activity, the OnStart () method is a good place to verify that some of the necessary system features are available.

@Overrideprotected void OnStart () {Super.onstart (); AlwaysCall the   superclass method  First//The activity  is either being restarted or s  tarted  for the   first time/So this is  where we should make sure that GPS  is enabled Locationmanager Locationmanager = (locationmanager) getsystemservice (context.location _service);Boolean gpsenabled = locationmanager.isproviderenabled (Locationmanager.gps_provider); if (!gpsenabled) {// Create A dialog here This requests the user  to enable GPS,  and use an intent  with the Android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS ACTION //  to Tak    E The user  to the Settings screens to enable GPS  when they click "OK"  }} @Overrideprotected void Onrestart () {Super.onrestart ();AlwaysCall the   superclass method  first/Activity being restarted from  stopped state}

When the system destory our activity, it calls the OnDestroy () method for the activity. Because we are doing the freeing of resources in the OnStop method, the Ondestory method is the last thing we want to do is to clear the areas that could lead to a memory leak. It is therefore necessary to ensure that those threads are destroyed and all operations are stopped.

Re-create activity

In several scenarios, activity is destory due to normal program behavior. For example, when the user clicks the Back button or activity by calling Activity.html#finish () ">finish () to emit a stop signal. It is also possible for the system to close the background process when the activity is in the stop state for a long time, or when the foreground activity requires more system resources, in order to obtain more memory.

When the activity is done because the user clicks the Back button or the activity ends himself by calling finish (), the system loses a reference to the activity instance, because this behavior means that the activity is no longer needed. However, if the activity is destory due to tight system resources, the system will have a record of the activity when the user returns to the activity, The system re-creates a new activity instance using the saved record data, which describes the state of the activity when it is destory. The data stored by the system to restore the previous state is called "instance", which is a key-value pairs that is stored in the bundle object. (Note the description here, which is important to understand the timing of onsaveinstancestate execution)

Caution: Your activity will be destroyed and recreated each time you rotate the screen. When the screen changes direction, the system will destory with the recreate foreground activity, because the screen configuration is changed, your activity may need to load other alternative resources (such as layout).
By default, the system uses a Bundle instance to hold information from each view object (such as entering text content in EditText). Therefore, if the activity is destroyed and recreated, the layout status information is automatically restored to its previous state. However, activity may have more state information that you want to recover, such as logging user progress member variables (member variables).

Note: In order for the Android system to restore the state of the view in activity, each view must have a unique ID, defined by Android:id.
in order to save additional data to saved instance state. There is an extra callback function in the life cycle of the activity, you must override this function. The callback function is not shown in the picture example in the previous lesson. This method is Activity.onsaveinstancestate (Android.os.Bundle) >onsaveinstancestate (), which is called by the system when the user leaves the activity. When the system calls this function, the system passes the bundle object when the activity is abnormally destory, so that we can add additional information to the bundle and save it to the system. If the system wants to recreate the activity instance after the activity is destory, the previous bundle object (System) is passed to the activity.onrestoreinstancestate of your activity ( Android.os.Bundle) >onrestoreinstancestate () method with the OnCreate () method.

Figure 2. When the system starts to stop activity, it is called to Activity.onsaveinstancestate (Android.os.Bundle) only if the activity instance will need to be recreated >onsaveinstancestate () (1), in which additional state data can be specified in the Bunde. If the Activity is destroyed and the instance needs to be recreated, the system passes the state data in (1) to OnCreate () (2) and Activity.onrestoreinstancestate ( Android.os.Bundle) >onrestoreinstancestate () (3).

(Usually, jumping to other activity or clicking Home will cause the current activity to execute onsaveinstancestate, Because the activity in this situation is likely to be destory and need to save the state for subsequent recovery use, and from the jump activity click Back to return to the previous activity, then the activity before the jump is to perform a fallback operation, So in this case the onsaveinstancestate will not be executed, because the activity cannot have operations that need to be rebuilt)

Save Activity status

When our activity starts stop, the system calls Onsaveinstancestate (), and activity can save state information with a collection of key-value pairs. This method saves the state information of the activity view by default, such as the text in the EditText component or the sliding position of the ListView.

In order to save additional state information for the activity, you must implement Onsaveinstancestate () and add key-value pairs to the Bundle object, for example:

static   Final  String state_score =  "Playerscore" ; static  final  String state_level =  "PlayerLevel" ; ....  @Override  public  void  onsaveinstancestate  (Bundle savedinstancestate) {//Save the user ' s current game state  Savedinstancestate.putint (State_score, MCu    Rrentscore);    Savedinstancestate.putint (State_level, mcurrentlevel); //always call the superclass so it can save the view hierarchy state  super . Onsaveinstancestate (savedinstancestate);}  

Note: The parent class implementation of the Onsaveinstancestate () method must be called so that the default parent class implementation can save the view state information.

Resume Activity Status

When activity is rebuilt from destory, we can restore the saved state from the bundle of activity that the system passes. Both the OnCreate () and the Onrestoreinstancestate () callback methods receive the same bundle, which contains the same instance state information.

Because the OnCreate () method is called when the first time a new activity instance is created and the instance that was destory before it is recreated, we must detect if it is null before attempting to read the Bundle object. If it is null, the system creates a new activity instance instead of recovering the activity that was previously destory.

Here's an example: the demo restores some data in the OnCreate method:

 @Override  protected  void  oncreate  ( Bundle savedinstancestate) {super . OnCreate (savedinstancestate); //always call the superclass first  //Check whether we ' re recreating a Previously destroyed instance  if  (savedinstancestate! = null ) {//Restore value of members from saved state  Mcurren        Tscore = Savedinstancestate.getint (State_score);    Mcurrentlevel = Savedinstancestate.getint (state_level); } else  {//Probably initialize members with default V Alues for a new instance } ...}  

We can also choose to implement Onrestoreinstancestate () instead of recovering the data in the OnCreate method. The Onrestoreinstancestate () method executes after the OnStart () method. The system only calls Onrestoreinstancestate () when there is state information that needs to be restored, so you do not need to check if the Bundle is null.

publicvoidonRestoreInstanceState(Bundle savedInstanceState) {    // Always call the superclass so it can restore the view hierarchy    super.onRestoreInstanceState(savedInstanceState);    // Restore state members from saved instance    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);}

Note: As with the previous save, it is always necessary to call the parent class implementation of the Onrestoreinstancestate () method so that the default parent class implementation can save the view state information. More about recreate our activity due to changes in runtime state.

What does the Android activity life cycle do?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.