Simplest Android Activity Lifecycle

前端 未结 9 1317
礼貌的吻别
礼貌的吻别 2020-12-13 20:28

I noticed that the Android Developers Activity section has been updated since I started my app, but I am still unclear what the simplest Activity Lifecycle is.

As fa

9条回答
  •  忘掉有多难
    2020-12-13 20:43

    Are you looking for this?

    To further answer your question, yes, as you can plainly see from the above diagram the "simplest" (i.e. smallest number of method calls) lifecycle is indeed onCreate(); onStart(); onResume(); onPause();.

    You should also know about onSaveInstanceState() and onRetainNonConfigurationInstance(). These are NOT lifecycle methods.

    All these methods are very well documented. Please read this documentation thoroughly.

    To clarify things further, here are a couple of real-life scenarios:

    1. Activity is running, other activities come on top of it, onPause is called. System runs out of memory, calls onSaveInstanceState, kills activity. User pressed back a few times, activity has to be re-instantiated (preferably using the data saved in onSaveInstanceState).
    2. Activity is running, user presses back. At this point onPause->onDestroy are called, without calling onSaveInstanceState.

    You should understand the essential difference between onPause and onSaveInstanceState. The former is always called, while the latter is only called when the activity instance might be re-instantiated in the future. Following this train of thought, your users will expect two things:

    1. When they navigate away from your Activity and later come back to it, they want it in the exact same instance that they left it (this would be achieved using onSaveInstanceState). They don't expect that if they exit your activity. However:
    2. They will expect that data they have entered will be persisted (which will be done in onPause). For example, if they started composing a message, they'll expect to see it as a draft the next time they come back, even if they exited the activity.

    You should understand how these methods are supposed to be used in order to get what your users expect. How you actually use them is up to you, your needs, and your app's nature.

提交回复
热议问题