Chapter 1. Getting Started: Diving In
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.
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.
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.
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.
Hereâs how activities and layouts work together when you run an app on your device:
Android starts the appâs main activity.
The activity tells Android to use a specific layout.
The layout is displayed on the device.
The user interacts with the layout.
The activity responds to these interactions, and updates the displayâ¦
â¦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:
Set up a development environment.
We need to install Android Studio, which includes all the tools you need to develop Android apps.
Build a basic app.
Weâll build a simple app using Android Studio that will display some sample text on the screen.
Run the app.
Weâll run the app on a physical device, and a virtual one, to see it up and running.
Change the app.
Finally, weâll tweak the app we created, and run it again.
Android Studio: your development environment
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:
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:
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.â
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.
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.
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:
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.
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):
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:
Kotlin and XML source files
Android Studio automatically created an activity file named MainActivity.kt, and a layout named activity_main.xml.
Resource files
These include default image files, themes the app might use, and any common
String
values used by the app.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.
Configuration files
The configuration files tell Android whatâs included in the app, and how the app should run.
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.
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.
The story so far
In the chapter so far, weâve done two things:
We set up the development environment.
Weâre using Android Studio to develop Android apps, so you needed to install it on a machine.
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
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
The Kotlin source files get compiled to bytecode.
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.
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.
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.
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.
Letâs run through what just happened.
What just happened?
Letâs break down what happens when you run the app:
Android Studio installs the app on the device.
If the device is virtual, it waits for the emulator to start before installing the app.
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.MainActivity specifies that it uses the layout activity_main.xml.
The layout is displayed on the screen.
The text âHello World!â appears in the center of the screen.
Letâs refine the app
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.
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.
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.
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.
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:
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:
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:
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!â
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:
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.
Android uses MainActivity.kt to create the activity object MainActivity.
MainActivity specifies that it uses the layout activity_main.xml.
The layout displays the text âPow!â in the center of the app on the device.
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!â
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
Youâve got Chapter 1 under your belt and now youâve added Android basic concepts to your toolbox.
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.