Android onStop/onDestroy - when might these be used?

后端 未结 3 877
萌比男神i
萌比男神i 2021-02-14 08:21

Looking at the Activity Life Cycle diagram, I notice that onPause() and onStop() can both lead to the \"process\" being killed. This would require

相关标签:
3条回答
  • 2021-02-14 08:27

    Another example would be to register and unregister a broadcast receiver.

    Note that usually these things are placed in onResume and onPause, the difference is subtle though, onResume/onPause are called when the activity gets placed behind another activity, onStart/onStop are called when the activity is no longer visible in the screen.

    0 讨论(0)
  • 2021-02-14 08:31

    If I got your question right: It depends what you want to do with your application. Let's say you are programming application that uses GPS. In the onStop() which is called when the activity is no longer visible to the user, you can remove these requests. Or you can stop the some service if your application is running any. Or you can save preferences (not recommended, do it in onPause() instead), or you can close permanent connection to a server.....If I think of anything else, I'll add more...

    0 讨论(0)
  • 2021-02-14 08:33

    If you have read the doc further, you'll see following:

    Saving activity state

    The introduction to Managing the Activity Lifecycle briefly mentions that when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it "resumes"), those changes are still there.

    However, when the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate the Activity object if the user navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was. In this situation, you can ensure that important information about the activity state is preserved by implementing an additional callback method that allows you to save information about the state of your activity and then restore it when the the system recreates the activity.

    Summary: After completing onStop() Activity object is still alive in memory. And this will help the system to restore the activity.

    Very basic example: consider you are showing your activity to user, and suddenly your friend calls you! Rest you can understand..

    So now it it up to you that, which are the resources/objects/connections should be released on which event.

    0 讨论(0)
提交回复
热议问题