Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Programming with Kotlin for Beginners

You're reading from  Android Programming with Kotlin for Beginners

Product type Book
Published in Apr 2019
Publisher Packt
ISBN-13 9781789615401
Pages 698 pages
Edition 1st Edition
Languages
Author (1):
John Horton John Horton
Profile icon John Horton

Table of Contents (33) Chapters

Android Programming with Kotlin for Beginners
Contributors
Preface
1. Getting Started with Android and Kotlin 2. Kotlin, XML, and the UI Designer 3. Exploring Android Studio and the Project Structure 4. Getting Started with Layouts and Material Design 5. Beautiful Layouts with CardView and ScrollView 6. The Android Lifecycle 7. Kotlin Variables, Operators, and Expressions 8. Kotlin Decisions and Loops 9. Kotlin Functions 10. Object-Oriented Programming 11. Inheritance in Kotlin 12. Connecting Our Kotlin to the UI and Nullability 13. Bringing Android Widgets to Life 14. Android Dialog Windows 15. Handling Data and Generating Random Numbers 16. Adapters and Recyclers 17. Data Persistence and Sharing 18. Localization 19. Animations and Interpolations 20. Drawing Graphics 21. Threads and Starting the Live Drawing App 22. Particle Systems and Handling Screen Touches 23. Android Sound Effects and the Spinner Widget 24. Design Patterns, Multiple Layouts, and Fragments 25. Advanced UI with Paging and Swiping 26. Advanced UI with Navigation Drawer and Fragment 27. Android Databases 28. A Quick Chat Before You Go Other Book You May Enjoy Index

Chapter 6. The Android Lifecycle

In this chapter, we will familiarize ourselves with the lifecycle of an Android app. The idea that a computer program has a lifecycle might sound strange at first, but it will soon make sense.

The lifecycle is the way that all Android apps interact with the Android OS. In the same way that the lifecycle of humans enables them to interact with the world around them, we have no choice but to interact with the Android lifecycle and we must be prepared to handle numerous unpredictable events if we want our apps to survive.

We will explore the phases of the lifecycle that an app goes through, from creation to destruction, and how this helps us know where to put our Kotlin code, depending on what we are trying to achieve.

In this chapter, we will explore the following topics:

  • The life and times of an Android app

  • The process of overriding and the override keyword

  • The phases of the Android lifecycle

  • What exactly we need to know and do to code our apps

  • A lifecycle demonstration...

The life and times of an Android app


We have talked a bit about the structure of our code; we know that we can write classes, and within those classes we have functions, and these functions contain our code, which gets things done. We also know that when we want the code within a function to run (that is, be executed), we call that function by using its name.

Additionally, in Chapter 2, Kotlin, XML, and the UI Designer, we learned that Android itself calls the onCreate function just before the app is ready to start. We saw this when we output to the logcat window and used the Toast class to send a pop-up message to the user.

In this chapter, we will examine what happens throughout the lifecycle of every app that we write; that is, when it starts, ends, and the stages in between. What we will see is that Android interacts with our app on numerous occasions each time that it is run.

How Android interacts with our apps

Android interacts with our apps by calling functions that are contained within...

A simplified explanation of the Android lifecycle


If you have ever used an Android device, you have probably noticed that it works quite differently to many other operating systems. For example, you can be using an app on your device, perhaps checking what people are doing on Facebook.

Then, you get an email notification and you tap the notification to read it. Halfway through reading the email, you might get a Twitter notification and, because you are waiting on important news from someone you follow, you interrupt your email reading and change apps to Twitter with a touch.

After reading the tweet, you fancy a game of Angry Birds; however, halfway through the first fling, you suddenly remember the Facebook post. So, you quit Angry Birds and tap on the Facebook icon.

You will likely resume Facebook at the exact same point that you left it. Afterward, you could then go back to reading the email, decide to reply to the tweet, or start an entirely new app.

All this toing and froing takes quite...

How we handle the lifecycle phases


When we are programming an app, how do we interact with this complexity? The good news is that the Android code that was autogenerated when we created our first project does most of it for us.

As we have discussed, we just don't see the functions that handle this interaction, but we do have the opportunity to override them and add our own code to that phase if we need to.

This means that we can get on with learning Kotlin and making Android apps until we come to one of the occasional instances where we need to do something in one of the phases.

Note

If our app has more than one activity, they will each have their own lifecycle. This doesn't have to complicate things and, overall, it will make things easier for us.

The following list offers a quick explanation of the functions provided by Android to manage the lifecycle phases. To clarify our discussion of lifecycle functions, they are listed next to their corresponding phases that we have been discussing....

The lifecycle demo app


In this section, we will do a quick experiment that will help to familiarize us with the lifecycle functions that our app uses and give us a chance to play around with a bit more Kotlin code.

Follow these steps to start a new project and then we can add some code:

  1. Start a new project and choose the Basic Activity project template; this is because during this project, we will also look at the functions that control the app menu and the Empty Activity option doesn't generate a menu.

  2. Call it Lifecycle Demo. The code is in the download bundle in the Chapter06/Lifecycle Demo folder, should you wish to refer to it or copy and paste it.

  3. Keep the other settings as they have been in all our example apps so far.

  4. Wait for Android Studio to generate the project files and then open the MainActivity.kt file in the code editor (if it is not opened for you by default) by left-clicking on the MainActivity tab above the editor.

We will only need the MainActivity.kt file for this demonstration...

Some other overridden functions


You may have noticed that there are two other autogenerated functions in the code of all our projects using the Basic Activity template. They are onCreateOptionsMenu and onOptionsItemSelected. Many Android apps have a pop-up menu, so Android Studio generates one by default when using the Basic Activity template, including the outline of the code to make it work.

You can see the XML that describes the menu in res/menu/menu_main.xml from the project explorer. The key lines of XML code are as follows:

<item
      android:id="@+id/action_settings"
      android:orderInCategory="100"
      android:title="@string/action_settings"
      app:showAsAction="never" />

This describes a menu item with the Settings text. If you run any of our apps built with the Basic Activity template, you will see the button as shown in the following screenshot:

If you tap the button, you can see it in action as follows:

So, how do the onCreateOptionsMenu and onOptionsItemSelected functions...

The structure of Kotlin code – revisited


We have already seen that each time we create a new Android project, we also create a new package; this is a kind of container for the code that we write.

We have also learned about and played around with classes. We have imported and taken direct advantage of classes from the Android API, such as Log and Toast. We have also used the AppCompatActivity class but in a different manner to that of Log and Toast. You might recall that the first line of code in all our projects so far, after the import statements, used the : notation to inherit from a class:

class MainActivity : AppCompatActivity() {

When we inherit from a class, as opposed to just importing it, we are making it our own. In fact, if you take another look at the line of code, you can see that we are making a new class, with a new name, MainActivity, but basing it on the AppCompatActivity class from the Android API.

Note

AppCompatActivity is a modified version of Activity. It gives extra features...

Summary


In this chapter, we have learned that it is not only us that can call our code; the operating system can also call the code contained within the functions that we have overridden. By adding the appropriate code to the various overridden lifecycle functions, we can be sure that the right code will be executed at the right time.

What we need to do now is to learn how to write some more Kotlin code. In the next chapter, we will start to focus on Kotlin and, because we have such a good grounding already in Android, we will have no problem practicing and using everything we learn.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019 Publisher: Packt ISBN-13: 9781789615401
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime}