No poetic female program apologise not good cook ~ reprint please indicate the source, the From Li Shiyu – blog.csdn.net/cjm24848365…

This is an old, old question that comes up in every interview.

How do we respond in a graceful and comprehensive way?

1. The normal Activity lifecycle.

1.1 First, the main line in the figure.

That is, the complete process of an activity from when it is opened to when it is invisible to when it is destroyed.

  • The Activity starts with the onCreat() method, which is used to initialize things like setContentView, setContent, Layout, and third-party SDK registration.

    Of course, we recommend lazy-loading or lazy-loading for our initialization, and our onCreat() should do as little as possible so that our application starts faster.

  • Once onCreat() is complete, our Activity will enter the onStart() state. OnStart () actually does some initialization as well. (Notice the difference)

  • Once onStart() has been executed, the interface is visible and interactive, which leads to the onResume() method. The onResume() method is used to do data recovery or related work when an activity exits and resumes in the background.

  • When we click the Back button, the current activity slowly disappears until it is destroyed, so it goes onPause()→ onStop() and onDestroy() completely.

This is the complete flow of an activity from when it starts, to when it disappears, to when it is destroyed.

1.2 Now talk about the next branch

① When our activity starts a dialog

  • OnPause () is executed when our Activiy launches a dialog that makes the part of our activity invisible.
  • When the dialog disappears, our activity comes back to the foreground fully visible, executes onResume(), and returns to the running state.

② When our activity starts another activity

For example, A activity starts B Activity.

  • Our ACTIVITY performs onPause() while B activity has not completely covered A activity.
  • When B activity is fully displayed, our A activity enters the onStop() state.
  • When B activity exits and comes back to A activity, our A activity should be displayed again, It will go through onRestart() and then re-execute onStart() and onResume() to return to the normal state of our activity.

A starts B and returns A life cycle print from B:

2. Abnormal circumstances

  • Let’s say we open a new app that makes our current app invisible (like pressing the home button) and hangs in the background.
  • If there is insufficient memory in the process of being hung in the background, our app may be killed by our system to the whole process.

What should we do if our app is killed by the system?

At this point we can use:

  • OnSaveInstanceState () saves the data

  • Restore data in onRestoreInstanceState() or onCreate()

Accumulate drip, do yourself ~