Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

Chapter 21. Threads and Starting the Live Drawing App

In this chapter, we will get started on our next app. This app will be a kid's-style drawing app where the user can draw on the screen using their finger. The drawing app that we create will be slightly different, however. The lines that the user draws will be comprised of particle systems that explode into thousands of pieces. We will call the project Live Drawing.

To achieve this, we will cover the following topics in this chapter:

  • Getting started with the Live Drawing app

  • Learning about real-time interaction, sometimes referred to as a game loop

  • Learning about threads

  • Coding a real-time system that is ready to draw in

Let's get started!

Creating the Live Drawing project


To get started, create a new project in Android Studio and call it Live Drawing. Use the Empty Activity project and leave the rest of the settings at their defaults.

Similar to the two drawing apps from the previous chapter, this app consists of Kotlin files only, and no layout files. The Kotlin files and all the code up to the end of this chapter can all be found in the Chapter21 folder of the download bundle. The complete project can be found in the Chapter22 folder of the download bundle.

Next, we will create empty classes that we will code throughout the project over the next two chapters. Create a new class called LiveDrawingView, a new class called ParticleSystem, and a new class called Particle.

Looking ahead at the Live Drawing app


As this app is more in-depth and needs to respond in real time, it is necessary to use a slightly more in-depth structure. At first, this may seem like a complication, but in the long run, it will make our code simpler and easier to understand.

We will have four classes in the Live Drawing app, as follows:

  • MainActivity: The Activity class provided by the Android API is the class that interacts with the operating system (OS). We have already seen how the OS interacts with onCreate when the player clicks on the app icon to start an app. Rather than have the MainActivity class that does everything, this Activity-based class will just handle the startup and shutdown of our app, and offer some assistance with initialization by calculating the screen resolution. It makes sense that this class will be of the Activity type and not AppCompatActivity. However, as you will soon see, we will delegate interaction through touches to another class, that is, the same...

Coding the MainActivity class


Let's get started with coding the Activity-based class. As usual, the class is called MainActivity, and it was autogenerated for us when we created the project.

Edit the class declaration and add the first part of the code for the MainActivity class:

import android.app.Activity
import android.os.Bundle
import android.graphics.Point

class MainActivity : Activity() {

    private lateinit var liveDrawingView: LiveDrawingView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)

        liveDrawingView = LiveDrawingView(this, size.x)

        setContentView(liveDrawingView)

    }
}

The preceding code shows several errors that we will talk about shortly. The first thing to note is that we are declaring an instance of our LiveDrawingView class. Currently, this is an empty class:

private lateinit var liveDrawingView...

Coding the LiveDrawingView class


The first thing we will do is solve the problem of our LiveDrawingView class not being of the View type and having the wrong constructor. Update the class declaration as follows:

class LiveDrawingView(
        context: Context,
        screenX: Int)
    : SurfaceView(context){

You will be prompted to import the android.view.SurfaceView class, as shown in the following screenshot:

Click on OK to confirm.

SurfaceView is a descendant of View and now LiveDrawingView is, by inheritance, also a type of View. Look at the import statement that has been added. This relationship is made clear, as highlighted in the following code:

android.view.SurfaceView

Note

Remember that it is because of polymorphism that we can send descendants of View to the setContentView function in the MainActivity class, and that it is because of inheritance that LiveDrawingView is now a type of SurfaceView.

There are quite a few descendants of View that we could have extended to fix this initial...

The game loop


So, what is a game loop anyway? Almost every live drawing, graphics-based app, and game has a game loop. Even games that you might not expect, such as turn-based games, still need to synchronize player input with drawing and AI, while following the rules of the underlying OS.

There is a constant need to update the objects in the app, such as by moving them and drawing everything in its current position while simultaneously responding to user input:

Our game loop comprises three main phases:

  1. Update all game and drawing objects by moving them, detecting collisions, and processing the AI, such as particle movements and state changes

  2. Based on the data that has just been updated, draw the frame of animation in its latest state

  3. Respond to screen touches from the user

We already have a draw function for handling this part of the loop. This suggests that we will have a function to do all the updating as well. We will soon code the outline of an update function. In addition, we know that...

Threads


So, what is a thread? You can think of threads in programming in the same way as you do threads in a story. In one thread of a story, we might have the primary character battling the enemy on the frontline, while in another thread, the soldier's family are living, day to day. Of course, a story doesn't have to have only two threads – we could introduce a third thread. For instance, the story also tells of the politicians and military commanders making decisions, and these decisions then subtly, or not so subtly, affect what happens in the other threads.

Programming threads are just like this. We create parts or threads in our program that control different aspects for us. In Android, threads are especially useful when we need to ensure that a task does not interfere with the main (UI) thread of the app, or if we have a background task that takes a long time to complete and must not interrupt the main thread of execution. We introduce threads to represent these different aspects for...

Implementing the game loop with a thread


Now that we have learned about the game loop and threads, we can put it all together to implement our game loop in the Living Drawing project.

We will add the entire code for the game loop, including writing code in two functions in the MainActivity class to start and stop the thread that will control the loop.

Note

Reader challenge

Can you work out for yourself how the Activity-based class will start and stop the thread in the LiveDrawingView class?

Implementing Runnable and providing the run function

Update the class declaration by implementing Runnable, as shown in the following highlighted code:

class LiveDrawingView(
        context: Context,
        screenX: Int)
    : SurfaceView(context), Runnable {

Notice that we have a new error in the code. Hover the mouse cursor over the word Runnable, and you will see a message informing you that we need to implement the run function just as we discussed during the discussion on interfaces and threads in the...

Running the app


Click on the play button in Android Studio and the hard work and theory of the chapter will come to life:

You can see that we now have a real-time system created with our game loop and a thread. If you run this on a real device, you will easily achieve 60 frames per second at this stage.

Summary


This was probably the most technical chapter so far. We explored threads, game loops, timing, using interfaces, and the Activity lifecycle – it's a very long list of topics to cram in.

If the exact interrelationship between these things is still not entirely clear, it is not a problem. All you need to know is that when the user starts and stops the app, the MainActivity class will handle starting and stopping the thread by calling the LiveDrawingView class's pause and resume functions. It achieves this through the overridden onPause and onResume functions, which are called by the OS.

Once the thread is running, the code inside the run function executes alongside the UI thread that is listening for user input. As we call the update and draw functions from the run function at the same time as keeping track of how long each frame is taking, our app is ready to rock and roll.

We just need to allow the user to add some particles to their artwork, which we can then update in each call to...

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 2019Publisher: PacktISBN-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.
undefined
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

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton