onStop vs onDestroy

耗尽温柔 提交于 2019-12-05 18:22:16

问题


I have tried to research exactly when the onDestroy method is called for an activity, but I've read some confusing and conflicting information. In general, my question is: under what circumstances is the onDestroy method actually called on an activity? More specifically, if I have two activities, activity A and activity B, if activity A is running and I create an intent and switch to activity B, is activity A only stopped, or is it destroyed?


回答1:


Like stated in the official documentation:

onDestroy()

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

In your example the Activity A is stopped and could be destroyed by the System


Note per documentation link above:
…do not count on [onDestroy()] being called as a place for saving data … [see] either onPause() or onSaveInstanceState(Bundle).



回答2:


onDestroy() is called whenever:

  • The user takes out the activity from the "recent apps" screen.
  • The user takes out the activity from the "recent apps" screen.

onStop() is called whenever:

  • The user leaves the current activity.

So in your example, when the user launches Activity B, Activity A called onStop().

EDIT: The onDestroy() method is not always being called, according to the documentation. onStop() is always called beginning with Honeycomb, so move code you explicitly need to do before the activity stops to there.

Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. https://developer.android.com/reference/android/app/Activity#ActivityLifecycle

Hope this helped :D



来源:https://stackoverflow.com/questions/29355290/onstop-vs-ondestroy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!