Skip to content Skip to sidebar Skip to footer

How To Close An Activity While Going Through The Life Cycle Destruction?

What is the android way of closing/finishing an activity and still wanting it to go through onPause, onStop and onDestroy? I am aware of Activity.finish(), however that will only

Solution 1:

Calling Activity.finish does go through the activity life cycle: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

Also the documentation for onDestroy() states:

Note: do not count on this method being called as a place for saving data!

The onPause() states:

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothingis lost if there are not enough resources to start the new activity without first killing this one. This is also a good place todo things likestop animations and other things that consume a noticeable amount of CPU inorderto make the switch to the next activity as fast as possible, orto close resources that are exclusive access such as the camera.

And one last thing, for onStop():

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

Which leaves you just with onPause() as the method to override and perform some saving stuff. And it is indeed called.

In found a related question here: finish() and the Activity lifecycle

Solution 2:

As per the documentation, "if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience."

Which means, OnPause() is the correct method for DB operations, but if they are too heavy as to block the UI transition, only then they should be done in OnStop()

Post a Comment for "How To Close An Activity While Going Through The Life Cycle Destruction?"