Android Applications are structured around Activities. Understanding how Activities work and structuring your code within that framework is key to creating successful Android applications. Do not try to fight this: I know from hard personal experience that this does not work.
Here is the first thing you need to know about Android Activities, and understanding this will shape everything you do while coding them in the future:
Activities can be fucking destroyed and recreated at any time – even while the user is interacting with them.
Do you understand this and the implications of this? Probably not, but I’ll outline the implications of this over a few blog posts and how to work with it.
When your activity is destroyed, you lose everything – all your variables, everything you’ve setup, popup alerts, the Activity object itself. All gone.
Here are some times that an Activity will be destroyed and recreated:
- You rotate your Android
- You open or close a Keyboard
- Another Activity is showing and Android needs the memory
In Android parlance, these are called “Configuration Changes“. There are ways to block this from happening, but I suggest it’s better to roll with the punches and “do the right thing”.
Fortunately Android destroys and recreates Activities in a well-defined structured manner and provides the proper places (albeit Java-clumsy) to save and restore the state so that the user won’t see that the whole interface they were looking at was destroyed and remade. More about this soon.