Chapter 1. Getting Started: Diving In

image

Android is the world’s most popular mobile operating system.

And there are billions of Android users worldwide, all waiting to download your next great idea. In this chapter, you’ll find out how to start turning your ideas into reality by building a basic Android app, and updating it. You’ll learn how to run it on physical and virtual devices. Along the way, you’ll meet two of the core components of all Android apps: activities and layouts. Let’s dive in…

Welcome to Androidville

Android is the world’s most popular mobile platform. At last count, there were over three billion active Android devices worldwide, and that number is still growing.

Android is a comprehensive open source platform based on Linux and championed by Google. It’s a powerful development framework that includes everything you need to build great apps. What’s more, it enables you to deploy those apps to a wide variety of devices—phones, tablets, and more.

So what makes up a typical Android app?

We’re going to build Android apps using Kotlin and XML. We’ll explain things along the way, but you’ll need some understanding of Kotlin to get the most out of this book.

Activities define what the app does

Each Android app includes one or more activities. An activity is a special class —usually written in Kotlin—that controls the app’s behavior, and decides how to respond to the user. If the app includes a button, for example, you add code to the activity that says what the button should do when the user taps or clicks on it.

image

Layouts define what each screen looks like

A typical Android app is composed of one or more screens. You define what each screen looks like using a layout file, or more activity code. Layouts are usually defined using XML, and each screen can include components such as buttons, text, and images.

image

There may be extra files too

In addition to activities and layouts, Android apps often need extra resources such as image files and application data. You can add any extra files you need to the app.

image

Android apps are really just a bunch of files in particular directories. When you build your app, these files get bundled together, giving you an app you can run on your device.

Activities and layouts form the backbone of your app

In a typical app, activities and layouts work together to define the app’s user interface. The layouts tell Android how the different screen elements should be arranged, and the activities control the app’s behavior. If the app features a button, for example, the layout specifies its position, and the activity controls what happens when the user clicks on it.

image

Here’s how activities and layouts work together when you run an app on your device:

image
  1. Android starts the app’s main activity.

  2. The activity tells Android to use a specific layout.

  3. The layout is displayed on the device.

  4. The user interacts with the layout.

  5. The activity responds to these interactions, and updates the display…

  6. …which the user sees on the device.

Now that you have an idea about how Android apps are put together, let’s go ahead and build a basic Android app.

Here’s what we’re going to do

So let’s dive in and create an Android app. There are just a few things we need to do:

  1. Set up a development environment.

    We need to install Android Studio, which includes all the tools you need to develop Android apps.

  2. Build a basic app.

    We’ll build a simple app using Android Studio that will display some sample text on the screen.

  3. Run the app.

    We’ll run the app on a physical device, and a virtual one, to see it up and running.

  4. Change the app.

    Finally, we’ll tweak the app we created, and run it again.

image

Android Studio: your development environment

image

The best way of developing Android apps is to use Android Studio, the official IDE for Android app development.

Android Studio is based on IntelliJ IDEA, which you may already be familiar with. It includes a set of code editors, UI tools and templates, which are all designed to make your life in Androidville easier.

It also includes the Android SDK—or Android Software Development Kit—which is required for all Android app development. The Android SDK includes Android source files, and a compiler that’s used to compile your code into an Android format.

Here are some of the main components of the Android SDK:

image

You need to install Android Studio

As Android Studio includes all the tools and features you need in order to develop Android apps, we’re going to use it to build all of the apps featured in this book.

Before we go any further, you need to install Android Studio on your machine. There are more details about how to do this on the next page.

Install Android Studio

To get the most out of this book, you need to install Android Studio. We’re not including the full installation instructions here as they can get out of date pretty quickly, but you’ll be fine if you follow the online instructions.

First, check the Android Studio system requirements here:

https://developer.android.com/studio#Requirements

Note

These URLs sometimes change. If they don’t work, search for Android Studio and you should find the appropriate pages.

Then download Android Studio from here:

https://developer.android.com/studio

Note

These URLs sometimes change. If they don’t work, search for Android Studio and you should find the appropriate pages.

and follow the installation instructions

Once you’ve installed Android Studio, open it and follow the instructions to add the latest SDK tools and Support Libraries.

In this book, we’re using Android Studio 2020.3.1 (known as Arctic Fox). Make sure you install at least this version.

If you’ve previously installed an earlier version of Android Studio, we recommend that you restore the IDE’s default settings. To do this, go to the File menu, choose Manage IDE Settings, and then select the Restore Default Settings option.

Note

This resets any old settings Android Studio might be holding on to that could stop your code from running.

When you’re done, you should see the Android Studio welcome screen like this:

image

Let’s build a basic app

image

Now that you’ve set up your development environment, you’re ready to create your first Android app. Here’s what it will look like:

image

Let’s go ahead and build the app.

How to build the app

Whenever you create a new app, you need to create a new project for it. Make sure you have Android Studio open, and follow along with us.

1. Create a new project

The Android Studio welcome screen gives you a number of options. We want to create a new project, so make sure the Projects option is selected, then click on “New Project.”

image

2. Select a project template

You next need to specify the type of Android Studio project you want to create. We’re going to create an app with an empty activity that runs on a phone or tablet, so make sure the Phone and Tablet option is selected, and choose the Empty Activity option. You’ll find out more about what the Empty Activity option gives you a few pages ahead, but for now, click the Next button to move to the next step.

image

3. Configure your project

You now need to configure the project by specifying an app name, package name, and save location. Enter a name of “My First App” and a package name of “com.hfad.myfirstapp” and accept the default save location.

You also need to tell Android Studio which programming language you want to use, and specify a minimum SDK. This refers to the lowest version of Android the app will support: there’s more about SDK levels on the next page.

Select Kotlin for the language and choose a minimum SDK of API 21 so that the app will run on most devices. When you click on the Finish button, Android Studio will create the project. We’ll look at what this involves a couple of pages ahead.

image

You’ve created your first Android project

Once you’ve been through the New Project wizard, it takes Android Studio a minute or so to create the project. During this time, it does the following:

  • Images It configures the project to your specifications.

    Android Studio looks at the minimum SDK you want the app to support, and includes all of the files and folders needed for a basic valid app. It also sets up the package structure and names the app.

  • Images It adds some template code.

    The template code is comprised of a layout written in XML and an activity written in Kotlin. You’ll find out more about these later in the chapter.

When Android Studio has finished creating the project, it automatically opens it for you.

Here’s what our project looks like (don’t worry if it looks complicated—we’ll break it down over the next few pages):

image

Dissecting your new project

An Android app is really just a bunch of valid files in a particular folder structure, and Android Studio sets all of this up for you when you create a new app. The easiest way of looking at this folder structure is to use the explorer in the leftmost column of Android Studio.

The folder structure includes different types of files

The explorer contains all of the projects that you currently have open. Here, we have a single project named MyFirstApp, which is the one we’ve just created.

If you browse through the various folders in the explorer, you’ll see that the wizard has created various types of files and folders for you like this:

  • Images Kotlin and XML source files

    Android Studio automatically created an activity file named MainActivity.kt, and a layout named activity_main.xml.

  • Images Resource files

    These include default image files, themes the app might use, and any common String values used by the app.

  • Images Android libraries

    In the wizard, you specified the minimum SDK you want the app to be compatible with. Android Studio makes sure the app includes the relevant Android libraries for that version.

  • Images Configuration files

    The configuration files tell Android what’s included in the app, and how the app should run.

image

Let’s take a closer look at some of the key files and folders in your project.

Introducing the key files in your project

Android Studio projects use the Gradle build system to compile and deploy apps, and Gradle projects have a standard structure. Below are some of the key files and folders in that structure you’ll be working with.

To see this view of the folder structure, change the explorer view in Android Studio from Android to Project. You do this by clicking on the arrow at the top of the explorer pane, and selecting the Project option.

image
image

Edit code with the Android Studio editors

You view and edit files using the Android Studio editors. Double-click on the file you want to work with, and the file’s contents will appear in the middle of the Android Studio window.

The code editor

Most files get displayed in the code editor, which is just like a text editor, but with extra features such as syntax highlighting and code checking.

The design editor

If you’re editing a layout (for example activity_main.xml), you have an extra option. Rather than edit the code, you can use the design editor, which allows you to drag GUI components onto the layout, and arrange them how you want. The code editor and design editor give different views of the same file, so you can switch back and forth between the two.

image

The story so far

In the chapter so far, we’ve done two things:

  1. We set up the development environment.

    We’re using Android Studio to develop Android apps, so you needed to install it on a machine.

  2. We’ve built a basic app.

    We used Android Studio to create a new Android project.

You’ve had a glimpse of what the app looks like in Android Studio, and got a feel for how it hangs together. But what you really want is to see it running, right?

Android Studio lets you run an app in two ways: on a physical Android device, and on a virtual one. We’ll show you each approach a few pages ahead.

How to run the app on a physical device

image

If you have an Android device that’s running Lollipop or above, you can use it to run the app we’ve just created.

Note

You can check this by looking at the Android version in the device settings. Lollipop is version 5.0, so it needs to 5.0 or higher.

Here are the steps to run the app on a physical device:

1. Enable USB debugging on your device

To allow Android Studio to run apps on your device, you need to enable USB debugging. This feature is available in the “Developer options” setting, which is disabled by default.

On your device, go to Settings → About Phone and tap the build number seven times. This enables the developer options. Then, go to Settings → System → Advanced → Developer options, and turn on USB debugging.

Note

Yep, seriously.

image

2. Set up your computer to detect the device

If you’re using a Mac, you can skip this step.

If you’re using Windows, you’ll need to install a USB driver if one isn’t already there. The latest instructions are here:

https://developer.android.com/studio/run/oem-usb

If you’re using Ubuntu Linux, you need to create a udev rules file. The latest instructions on how to do this are here:

https://developer.android.com/studio/run/device#setting-up

3. Use a USB cable to plug your device into your computer

You will probably be asked if want to allow USB debugging. If so, check the “Always allow from this computer” option and choose OK.

When we created the app, we specified a minimum API level of 21 (Lollipop). Your device needs this version of Android or above for the app to run.

4. Run the app

Finally, select the device from the list of devices in Android Studio’s top toolbar (if it’s not there, on your device go to Settings → Connected devices, select USB, and choose the “File transfer” option). Then run the app by choosing “Run ‘app’” from the Run menu. Android Studio will build the project, install the app on your device, and launch it.

image

We’ll look at the app a few pages ahead, after we’ve seen how to run it on a virtual device.

How to run the app on a virtual device

If you don’t have an Android device on hand, or it doesn’t have the right version of Android, you can run the app on a virtual device instead. Running the app on a virtual device is useful if you want to see how the app looks on a type of device you don’t own, or test how it behaves on a different version of Android.

The Android SDK features a built-in emulator that you can use to set up one or more Android Virtual Devices (AVDs). Once you’ve set up an AVD, you can run the app on it as though it’s running on a physical device.

Note

You can find system requirements for using the emulator here: https://developer.android.com/studio/run/emulator#requirements

The emulator recreates the exact hardware environment of an Android device: from its CPU and memory through to the sound chips and the video display. The emulator is built on an existing emulator called QEMU (pronounced “queue em you”), which is similar to other virtual machine applications you may have used, like VirtualBox or VMWare.

The exact appearance and behavior of the AVD depends on how you set it up. If, say, you create an AVD based on a Pixel 3 running Android 11, it will look and behave just like a Pixel 3 running this version of Android on your computer.

image

Let’s set up an AVD so that you can see the app running in the emulator.

Create an Android Virtual Device (AVD)

There are a few steps you need to go through in order to set up an AVD within Android Studio. We’ll set up a Pixel 3 AVD running API level 30 (Android 11) so that you can see how the app looks and behaves running on this type of device. The steps are pretty much identical no matter what type of virtual device you want to set up.

Open the Android Virtual Device Manager

The AVD Manager allows you to set up new AVDs, and view and edit ones you’ve already created. Open it by selecting AVD Manager on the Tools menu.

If you have no AVDs set up already, you’ll be presented with a screen prompting you to create one. Click on the Create Virtual Device button.

image

Select the hardware

On the next screen, you’ll be prompted to choose a device definition. This is the type of device your AVD will emulate. You can choose a variety of phone, tablet, wear, or TV devices.

We’re going to see what the app looks like running on a Pixel 3 phone. Choose Phone from the Category menu and Pixel 3 from the list. Then click on the Next button.

image

Select a system image

Next, you need to select a system image. This specifies which version of Android you want to be on the AVD.

You need to choose a version of Android that’s compatible with the app you’re building. It must be at least the minimum SDK that the app supports.

When you created your Android project, you specified that the minimum SDK is API level 21. This means that you need to choose a system image that’s for API level 21 (Lollipop) or above. If you choose an older version of Android than this, the app won’t be able to run on the device.

Here, we’re going to see what the app looks like on a relatively new version of Android, so choose the system image with a release name of R and a target of Android 11.0 (API level 30). Then click Next.

image

Verify the AVD configuration

On the next screen, you’ll be asked to verify the configuration. This screen summarizes the options you chose over the last few screens, and gives you the option of changing them. Accept the options, and click on the Finish button.

image

The virtual device gets created

When you click on the Finish button, the Device Manager creates the virtual device for you, and displays it in the AVD Manager’s list of virtual devices like this:

image

Check the new AVD is listed, then close the AVD Manager.

Run the app on the AVD

Once you’ve created the AVD, you can run the app on it.

To run the app, make sure that the virtual device is selected in the list of devices in Android Studio’s top toolbar, then run the app by choosing the “Run ‘app’” command from the Run menu.

The AVD can take a while to load, so while we wait, let’s take a look at what happens behind the scenes when you use the Run command.

image

Compile, package, deploy, run

The Run command doesn’t just run your app. It also handles all the preliminary tasks that are needed for the app to run.

Here’s an overview of what happens:

An APK file is an Android application package. It’s like a ZIP or JAR file for Android applications.

image
  1. The Kotlin source files get compiled to bytecode.

  2. An Android application package, or APK file, gets created.

    The APK file includes the compiled Kotlin files, along with any libraries and resources needed by the app.

  3. The APK is installed on the device.

    If the device is virtual, Android Studio launches the emulator and waits until the AVD is active before installing the APK.

    If the device is physical, it just installs the APK.

  4. The device starts the app’s main activity.

    The app is displayed on the device screen, and it’s all ready for you to play with.

Now that you know what happens when you use the Run command, let’s see what the app we’ve built looks like.

Images Test Drive

Make sure you’ve run the app on a physical or virtual device by choosing the “Run ‘app’” command from the Run menu.

Android Studio loads the app onto the device and starts it. The app name “My First App” appears at the top of the screen, and the text “Hello World!” is displayed in the center.

image

Let’s run through what just happened.

What just happened?

Let’s break down what happens when you run the app:

  1. Android Studio installs the app on the device.

    If the device is virtual, it waits for the emulator to start before installing the app.

    image
  2. Android starts the app’s main activity.

    It uses the code in MainActivity.kt (which Android Studio automatically included in the project) to create a MainActivity object.

    image
  3. MainActivity specifies that it uses the layout activity_main.xml.

    image
  4. The layout is displayed on the screen.

    The text “Hello World!” appears in the center of the screen.

    image

Let’s refine the app

image

So far in this chapter, you’ve built a basic Android app and seen it running on a physical or virtual device. Next, we’re going to refine the app.

At the moment, the app displays the sample text “Hello World!” that the wizard put in as a placeholder. You’re going to change that text to say something else instead. So what do we need to change in order to achieve that?

To answer that question, let’s take a step back and see how the app is currently built.

image

The app has one activity and one layout

When we built the app, we told Android Studio how to configure it, and the wizard did the rest. The wizard created an activity for us, and also a default layout.

The activity controls what the app does

Android Studio created an activity for us named MainActivity.kt. The activity specifies what the app does and how it should respond to the user.

The layout controls the app’s appearance

MainActivity.kt uses the layout Android Studio created for us named activity_main.xml. The layout specifies what the app looks like.

image

We want to change the appearance of the app by updating the text that’s displayed. This means that we need to update the file that controls what the app looks like, so we need to take a closer look at the layout.

What’s in the layout?

We want to change the sample “Hello World!” text that Android Studio created for us, so let’s start with the layout file activity_main.xml. Open it now (if it’s not already open) by finding the file in the app/src/main/res/layout folder in the explorer and double-clicking on it.

image

The design editor

As you learned earlier, there are two ways of viewing and editing layout files in Android Studio: through the design editor and through the code editor.

When you choose the design option, you can see that the sample text “Hello World!” appears in the layout as you might expect. But what’s in the underlying XML?

Let’s see by switching to the code editor.

image

The code editor

Switch to the code editor by clicking on the Code option at the top of the editor. This shows you the layout’s underlying XML.

Let’s take a closer look at the code.

activity_main.xml has two elements

Below is the code from activity_main.xml that Android Studio generated for us. We’ve left out some of the details you don’t need to think about just yet; we’ll cover them in more detail through the rest of the book.

Here’s the code:

image
image

As you can see, the code contains two elements.

The first is a <…ConstraintLayout> element. This is a type of layout element that tells Android how to display components on the device screen. There are various types of layout available for you to use, and you’ll find out more about these later in the book.

The most important element for now is the second element, the <TextView>. This element is used to display text to the user, in this case the text “Hello World!”

The key part of the code within the <TextView> element is the line starting with android:text. This is a text attribute that describes the text that should be displayed:

image

We’ll change the text to something else after you’ve had a go at the following exercise.

Update the text displayed in the layout

We want to change the text in activity_main.xml so that when we run the app, it displays something other than “Hello World!” We can do this by changing the text attribute in the layout’s <TextView> element:

image

The text attribute is defined inside the <TextView> element using the code android:text. It specifies what text should be displayed, in this case “Hello World!”

image

To update the text that’s displayed in the layout, simply change the value of the text attribute from "Hello World!" to some other text, such as "Pow!". The new code for the <TextView> element should look like this:

image

That’s the only change you need to make in order to update the text. Let’s see what happens when the code runs.

What the code does

Before we take the app for a test drive, let’s go through what the code does.

  1. Android uses MainActivity.kt to create the activity object MainActivity.

    image
  2. MainActivity specifies that it uses the layout activity_main.xml.

    image
  3. The layout displays the text “Pow!” in the center of the app on the device.

    image

Images Test Drive

Once you’ve edited the file, try running the app in the emulator again by choosing the “Run ‘app’” command from the Run menu, or clicking on the Run button. You should see that the app now says “Pow!” instead of “Hello World!”

image

Congratulations! You’ve now built and updated your first app, and learned how Android apps hang together in the process. We’ll build on this further in the next chapter by creating an app you can interact with.

Your Android Toolbox

image

You’ve got Chapter 1 under your belt and now you’ve added Android basic concepts to your toolbox.

image

Get Head First Android Development, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.