Introduction to the Android lifecycle
We have talked a bit about the structure of our code; that we write classes, and within those classes we have methods that contain our code. We also know that when we want the code within a method to run (be executed), we call that method by using its name.
Also, in Chapter 2, Java - First Contact, we learned that Android itself calls the onCreate
method just before the app is ready to start. We saw this when we outputted to the logcat and used the Toast
class to send a pop-up message to the user.
What we will look at now is what happens throughout the lifecycle of every app we write: when it starts and ends, as well as a few stages in between. And what we will see is that Android actually interacts with our app on numerous occasions, each and every time it is run.
It does so by calling methods that are contained within the Activity
class. Even if the method is not visible within our Java code, it is still being called by Android at the appropriate time. If this doesn't seem to make any sense, then read on.
Did you ever wonder why the onCreate
method had the strange-looking line of code just before it?
@Override
What is going on here is that, when you call onCreate
, we are asking Android to please use our overridden version, because we have some things to do at that time.
Furthermore, you might remember the odd-looking first line of code in the onCreate
method:
super.onCreate(savedInstanceState)
This is telling Android to call the original/official version of onCreate
before proceeding with our overridden version. This is not just a quirk of Android, method overriding is built into Java.
There are also quite a lot of other methods that we can optionally override, and they allow us to add our code at appropriate times within the lifecycle of our Android app.
The reason we need to care about the methods of our app that Android calls whenever it wants, is because they control the very life and death of our code. For instance, what if our app allows the user to type a moment of inspiration, perhaps a poem or vital reminder, into our hypothetical note-taking app, when halfway through the phone rings, our app disappears and the data (the note) is gone?
It is vital, and thankfully quite straightforward, that we learn when, why, and which methods Android will call as part of the lifecycle of our app. We can then know where we need to override methods to add our own code and where to add the real functionality (code) that defines our app. Let's examine the Android lifecycle, then we can move on to the ins and outs of Java, and we will know exactly where to put the code that we write.