As I dig into the coding of the next app, I’ve inevitably run into the Android activity lifecycle. Initial thought: Wow, that’s nerdy 🙂
The lifecycle pyramid
The picture below shows the “lifecycle pyramid”. Simplified the app transitions through a series of different states, from left to right with the occasional backtracking. This of course depends on how the user interacts with it.
First impressions
What first struck me was the way the different states are reached and how chaotic it seems. Having read a little more from the Android Training classes, it quickly made a lot more sense to me. The app is started, it has a “running” state, it can be paused and eventually terminated.
In the above pyramid there are quite a few arrows between the different states, illustrating the method calls that are being made by the JVM, when each transition occurs. This got me thinking; “Why not try it out and see what and when everything is invoked?”. The guys at Google of course already thought of this and made an example of this, but I’m more of a hands-on guy sometimes.
onResume and onPause?
The lesson I’m trying pass on here is this; When you start up you activity a series of methods gets called per default (OnCreate, OnStart and OnResume) and then you’re good to go. What surprised me is at if you hit the menu button, gets interrupted by a call or even if you rotate the screen, your activity gets destroyed and rebuilt. Of course you can’t be totally sure that it gets destroy on every occations, but you should program as if it did.
You should therefore always save your state when your activity gets paused (onPause), ’cause it might get destroyed. When you return to your activity, you should restore the state in the onResume method. This way you ensure that nothing is lost if your activity loses focus or the screen gets rotated.