Android Programming with Kotlin for Beginners
上QQ阅读APP看书,第一时间看更新

How Kotlin and Android work together

The Android Software Development Kit (SDK) is largely written in Java, because Kotlin is the new kid on the block; but when we tell Android Studio to turn our Kotlin code into a working app, it is merged together with the Java from the SDK in an intermediate form before being converted into a format called DEX code, which the Android device uses to convert into a running app. This is seamless to us as developers, but it is worth knowing (and, perhaps, is quite interesting) to know what is going on behind the scenes.

Whether you have programmed your app in Kotlin or Java, the resulting DEX code is the same. However, there are some significant advantages to working with Kotlin.

Kotlin is named after an island near St Petersburg, Russia. Kotlin is very similar to Apple's Swift language, so learning Kotlin now will stand you in very good stead for learning iPhone/iPad development.

Kotlin is the most succinct language, and therefore is the least error-prone, which is great for beginners. Kotlin is also the most fun language, mainly because the succinctness means you can get results faster and with less code. Google considers Kotlin an official (first-class) Android language. There are some other advantages to Kotlin that make it less error-prone and less likely to make mistakes that cause crashes. We will discover the details of these advantages as we proceed.

Loads of the most advanced, innovative, and popular apps were coded using Kotlin. Just a few examples include Kindle, Evernote, Twitter, Expedia, Pinterest, and Netflix.

Before we start our Android quest, we need to understand how Android and Kotlin work together. After we write a program for Android, either in Java or Kotlin, we click a button and our code is transformed into another form, a form that is understood by Android. This other form is called Dalvik Executable, or DEX code, and the transformation process is called compiling. When the app is installed on a device, the DEX code is transformed again by the operating system into an optimized executable state.

Note

We will see this process in action right after we set up our development environment later on in the chapter.

Android is a complex system, but you do not need to understand it in depth to be able to start making amazing apps.

Tip

A full understanding will come after using and interacting with it over time.

To get started, we only need to understand the basics. Android runs on a specially adapted version of the Linux operating system. So, what the user sees of Android is just an app running on yet another operating system.

Android is a system within a system. The typical Android user doesn't see the Linux operating system, and most probably doesn't even know it is there.

One purpose of this is to hide the complexity and diversity of the hardware and software that Android runs on, but, at the same time, exposing all its useful features. The exposure of these features works in two ways:

  • First, the operating system itself must have full access to the hardware, which it does.
  • Second, this access must be programmer-friendly and easy to use, and it is because of the Android application programming interface (API).

Let's continue by looking further into the Android API.

The Android API

The Android API is code that makes it easy to do exceptional things. A simple analogy could be drawn with a machine, perhaps a car. When you press on the accelerator, a whole bunch of things happen under the hood. We don't need to understand combustion or fuel pumps, because some smart engineer has made an interface for us; in this case, a mechanical interface – the accelerator pedal.

For example, the following line of code probably looks a little intimidating at this stage in the book, but it serves as a good example of how the Android API helps us:

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Once you learn that this single line of code searches for available satellites in space, communicates with them in their orbits around the Earth, and then retrieves your precise latitude and longitude on the surface of the planet, it becomes easy to glimpse the power and depth of the Android API.

That code does look a little challenging, even mind-boggling at this stage of the book, but imagine trying to talk to a satellite some other way!

The Android API has a whole bunch of code that has already been written for us to use as we like.

The question we must ask, and the one this book tries to answer, is as follows: how do we use all this code to do cool stuff? Or, to frame the question to fit the earlier analogy: how do we find and manipulate the pedals, steering wheel, and, most importantly, the sunroof of the Android API?

The answer to this question is the Kotlin programming language, and the fact that Kotlin was designed to help programmers handle complexity, avoid mistakes, and make fast progress. Let's look deeper into Kotlin and object-oriented programming (OOP).

Kotlin is object-oriented

Kotlin is an object-oriented language. This means that it uses the concept of reusable programming objects. If this sounds like technical jargon, another analogy will help. Kotlin enables us and others (like the Android API development team) to write code that can be structured based on real-world things, and here is the important part – it can be reused.

So, using the car analogy, we could ask the following question: if a manufacturer makes more than one car in a day, do they redesign every part for every car that comes off the production line?

The answer, of course, is no. They get highly skilled engineers to develop exactly the right components, honed, refined, and improved over years. Then, those same components are reused again and again, as well as being occasionally improved.

If you are going to be fussy about my analogy, then you can point out that each of the car's components must still be built from the raw materials using real-life engineers or robots. This is true.

What software engineers do when they write their code is build a blueprint for an object. We then create an object from their blueprint using code and once we have that object, we can configure it, use it, combine it with other objects, and more besides.

Furthermore, we can design blueprints ourselves and make objects from them. The compiler then transforms (manufactures) our bespoke creation into DEX code. Hey presto! We have an Android app.

In Kotlin, a blueprint is called a class. When a class is transformed into a real working "thing," we call it an object or an instance of the class.

Note

Objects in short.

We could go on making analogies all day long. As far as we care at this point, Kotlin (and most modern programming languages) is a language that allows us to write code once that can then be used repeatedly.

This is very useful because it saves us time, and allows us to use other people's code to perform tasks we might otherwise not have the time or knowledge to write for ourselves. Most of the time, we do not even need to see this code, or even know how it does its work!

One last analogy. We just need to know how to use that code, just as we need to learn how to drive a car.

So, some smart software engineers up at Android HQ write a desperately complex program that can talk to satellites, and as a result of this, in a single line of code, we can get our location on the surface of the planet. Nice.

Most of the Android API is written in another language (Java), but this doesn't matter to us as we have full access to the functionality (coded in Java) while using the more succinct Kotlin. Android Studio and the Kotlin compiler handle the complexities behind the scenes.

The software engineers have considered how they can make this code useful to all Android programmers who want to make amazing apps that use users' locations to do cool things. One of the things they will do is make features, such as getting the device's location in the world into a simple one-line task.

So, the single line of code we saw previously sets in action many more lines of code that we don't see, and don't need to see. This is an example of using somebody else's code to make our code infinitely simpler.

Tip

If the fact that you don't have to see all the code is a disappointment to you, then I understand how you feel. Some of us, when we learn about something, want to learn every intricate detail. If this is you, then be reassured that the best place to start learning how the Android API works internally is to use it as the API programmers intended. And, throughout the book, I will regularly point out further learning opportunities where you can find out the inner workings of the Android API. Also, we will be writing classes that are themselves reusable, kind of like our own API, except that our classes will focus on what we want our app to do.

Welcome to the world of OOP. I will constantly refer to OOP in every chapter, and there will be a big reveal in Chapter 10, Object-Oriented Programming.

Run that by me again – what, exactly, is Android?

To get things done on Android, we write code of our own, which also uses the code of the Android API. This is then compiled into DEX code, and the rest is handled by the Android device, which, in turn, runs on an underlying operating system called Linux, which handles the complex and extremely diverse range of hardware that is the different Android devices.

The manufacturers of Android devices and of the individual hardware components obviously know this too, and they write advanced software called drivers that ensure that their hardware (for example, CPU, GPU, GPS receivers, memory chips, and hardware interfaces) can run on the underlying Linux operating system.

The DEX code (along with some other resources) are placed in a bundle of files called an Android application package (APK), and this is what the device needs to run our app.

Tip

It is not necessary to remember the details of the steps that our code goes through when it interacts with the hardware. It is enough just to understand that our code goes through some automated processes to become the app that we will publish to the Google Play store.

The next question is: where exactly does all this coding and compiling into DEX code, along with APK packaging, take place? Let's look at the development environment that we will be using.

Android Studio

A development environment is a term that refers to having everything you need to develop, set up and ready to go in one place.

There is an entire range of tools needed to develop for Android, and we also need the Android API, of course. This whole suite of requirements is collectively known as the SDK. Fortunately, downloading and installing a single application will give us these things all bundled together. The application is called Android Studio.

Android Studio is an integrated development environment (IDE) that will take care of all the complexities of compiling our code and linking with the Android API. Once we have installed Android Studio, we can do everything we need inside this single application, and put to the back of our minds many of the complexities we have been discussing.

Tip

Over time, these complexities will become second nature. It is not necessary to master them immediately to make further progress.

So, we had better get our hands on Android Studio.