I hear people say a lot that the lifecycle callback functions in an Android Activity are confusing. Their names address the events that can occur from a memory management perspective, but they don't directly address things that the developer really pays attention to. Things like when is the view done loading into memory? and when is the view visible to the user?
I wanted to write a quick post to address this, because in many cases the best callback to use is not located in the standard set. The standard Activity callback functions are:
onCreate()
onStart()
onResume()
onPause()
onStop()
onDestroy()
Most Activity implementations will cycle through these functions, in order or with a few small internal loops, from one end to the other. The developer documentation on this (the link above) is good, but there are actually some hidden gems inside of the ActivityGroup documentation as well.
Mapping to More Useful Events
Here is a simple list of common things I see most often and where the best place to implement them would be in an Android Activity:
When should I close/unload/finish resources the visible view requires?
onPause()
: This method is the only one that you can be relatively
guaranteed will be called every time. In many situations, onStop()
gets
skipped, and it is usually too late if you wait for onDestroy()
.
When do I know the Activity is active and ready to process again?
onResume()
: This method, again, is a sure bet callback when the
Activity is coming back to life. Other methods, like onStart()
may be
surplanted by onRestart()
depending on the startup conditions.
When do I know the Activity is actually visible to the user?
onWindowFocusChanged()
: This is one that is slightly outside the normal
flow, but it is the best choice. Trying to implement changes that are
dependant on the Activity being visible in earlier callbacks like onResume()
provides not guarantees of visibility. In most cases, onResume()
is too
early and you may experience flickers during the transition. hasFocus
will
(of course) be true when this is called as part of a reappear event.
More About onWindowFocusChanged()
The Android documentation describes this as the best method to use when determining when the Activity becomes visible or invisible to the user. However, because it is not part of the normal lifecycle event flow, there are times when this function will be called that do not have to do with the Activity view appearing/disappearing during creation/destruction. This method will also be called when temporary interactions like dialogs come up in front of the Activity. This may be something to keep in mind as your implementation may be affected by this subtle difference.