Activity Lifecycle

  • The official documentation developer. The android. Google. Cn/guide/compo…

  • six

OnCreate -- onStart visible -- onResume focused -- onPause unfocused -- onStop not visible -- onDestoryCopy the code
  • OnRestart is called when it comes back to the foreground unseen

  • All lifecycle method rewrite implementations must call their parent class methods
  • Since activities often switch back and forth between paused and resumed, the logic of onResume and onPause should be lightweight
  • In some cases, onStop and onDestory may not be called. Therefore, some important data can be saved in onPause according to the actual situation. Time-consuming operations need to be handled by child threads

Classic scene

Scenario 1 Starting Activity A for the first time

//Activity A
onCreate -> onStart -> onResume
Copy the code

Scenario 2 Start Activity B on Activity A

//Activity A onPause ->(Activity A is overwritten by Activity B and stops)onStop ->(if Activity A finishes or is recovered by the system)onDestory //Activity B OnCreate -> onStart ->(Activity B waits until Activity A's onPause starts)onResumeCopy the code
  • If Activity B is fully transparent or dialog themed, Activity A does not continue onStop
  • OnPause cannot perform time-consuming operations

Scenario 3 returns from Activity B to Activity A

//Activity B onPause -> onStop -> onDestory //Activity A onRestart -> onStart -> onResume OnCreate -> onStart -> onResumeCopy the code

Scenario 4 Screen Lock and Unlock

// Lock screen onPause, not onStop // unlock onResumeCopy the code

Scenario 5 Tap the HOME button to initiate a call

OnPause ->onStop // Return to App onRestart -> onStart->onResume // The foreground Activity finishes or is recycled by the system. OnCreate -> onStart -> onResumeCopy the code

Life cycle things to do

onCreate

  • Call the setContentView method to set the layout
  • Define member variables and initialize data
  • Initialize views, controls, and UI elements
  • Configure the UI, bind data to lists, and so on
  • Associate the Activity with the ViewModel

The onCreate effort should be minimized so that the program will not be able to see the interface for too long. You can use the savedInstanceState parameter to restore some state, or null if it is created for the first time

onStart

  • Such as registering a broadcast that listens for UI changes
  • Recreate the resources released in onStop

onResume

  • Restore actions stopped in onPause, such as Camera preview
  • Start the animation

This means that the Activity is at the top of the Activity stack and gets focus

onPause

  • Release system resources, sensors (such as GPS) handles, cameras, etc
  • To stop the animation

This is not the place to save application or user data, make network calls, or perform database transactions; that is, it is not the place to do long work

The map navigation page is usually not released here because it is expected to still work

Minimize onPause workload to avoid slow Activity transitions

onStop

  • Resources that are no longer needed should be freed up

  • Switch from precise location updates to rough location updates as needed

  • Turn off those cpus that perform relatively intensive operations

  • Saves user content, such as a draft of a mailbox, to persistent storage

  • User preferences persist data or data in a database

  • Stop the Service that periodically updates data on the UI with the Service

This is where you can save application or user data, make network calls, or perform database transactions

onDestoty

  • Any resources that have not been released by a previous callback, such as onStop, should be released

It is not recommended to release resources in onDestroy because onDestroy may be executed late. You can use onPause or onStop to release resources with isFinishing judgment as required

Life cycle in exceptional cases

  • Running out of memory causes the Activity to be reclaimed by the system. Instead of terminating the Activity to free memory, the system terminates the process in which the Activity is running, destroying not only the Activity but also all other content running in that process
  • Configuration changes: horizontal/vertical switching, system language change, input device change, switch to multi-window mode (Android 7.0 Api 24)
  • Use the Application Manager in Settings to stop the application and terminate the process

The Activity is destroyed and then rebuilt

onSaveInstanceState

  • Super. OnSaveInstanceState is implemented in the preservation of the state of the view hierarchy structure logic

  • Stores instantaneous information about the Activity’s view Hierarchy state (such as the value of the input box and the position of the list after sliding). The saved data the system uses to restore the previous state is called instance state, which is a set of key-value pairs stored in the Bundle object. By default, the system uses the Bundle instance state to store information about each View object in the Activity layout. When the system destroys an Activity due to system constraints (such as configuration changes or memory stress), if the user tries to revert to the Activity, The system creates a new instance of the Activity using a set of saved data that describes its state when it was destroyed, restoring the layout state to its previous state without writing code.

  • Bundle objects are not suitable for holding large amounts of data, and serialization and deserialization in the main thread can cause memory consumption

  • Save temporary data mainly, save simple and lightweight interface state, if save a large amount of data should be processed with the ViewModel

  • Call before onStop

  • This method is not called to save the state when the Finish method is actively called and the return key is hit

onRestoreInstanceState

  • Super. OnRestoreInstanceState has implementation view hierarchy structure, the logic of the state of the recovery

  • The call comes after onStart

  • Can be used to restore some data saved in the onSaveInstanceState method

Switching between horizontal and vertical screens

  • When android:configChanges is not set for the Activity, the various life cycles are re-called for screen cuts, once for landscape and twice for portrait

  • When you set the Activity’s Android :configChanges=” Orientation “, the various life cycles will still be called again, and only once for landscape and portrait

  • Set up the Activity of the android: configChanges = “orientation” | “keyboardHidden, cut the screen each life cycle will not call again, will only implement onConfigurationChanged method

Q&A

1 What is the lifecycle if you call finish directly from onCreate?

Calling the onDestory method directly skips all other lifecycles, and in fact, calling the Finish method in any lifecycle skips all other lifecycles before that

2 When does onPause go, but not onStop?

  • Lock screen
  • Open an Activity with a fully transparent or dialog theme

3 When does an Activity not execute onDestory?

  • The main thread crashes abnormally

  • The application was forcibly killed

4 What is the Activity lifecycle when the status bar is pulled down?

The status bar, AlertDialog, Toast, etc., are displayed through the WindowManager.addView method, which has no impact on the Activity’s life cycle. In addition, onWindowFocusChanged(Boolean hasFocus) can be used to listen on the status bar. HasFocus false can indicate the drop-down status, which can be used to pause the video

Start an Activity lifecycle analysis for another application?

6 How to count the Activity working time?