© Grant Allen 2021
G. AllenAndroid for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6646-5_3

3. Your First Android Application, Already!

Grant Allen1  
(1)
LONDON, UK
 

With Android Studio in place on your computer, you are ready to begin creating your very first Android application. Yes, right now! For those readers who are not familiar with Java code development, do not panic. We will start our examples in this chapter with no assumed Java knowledge or know-how. For those readers who do know Java, read on in any case as we will cover the important first step of creating an Android Virtual Device, or AVD, on which to run the example in this chapter, as well as the examples in future chapters.

Creating Your First Android Virtual Device

One of the most useful features provided in the wider Android Studio integrated environment is the ability to create Android Virtual Devices, or AVDs. With an AVD, you get the ability to emulate a real Android device, controlling a range of its capabilities and features, without having to have an actual physical device.

The AVD approach isn’t meant to prohibit you from using a real device on which to test and use your applications, but if you think about the plethora of Android devices, versions, and form factors that we’ve touched on in the first two chapters, you can see how it would be impractical for you as a developer to own even a fraction of the number of devices found in the wild running Android. AVDs help you bridge the gap between what you have (and can afford) and what your user base will actually be using.

To start creating your first AVD, start Android Studio if it is not already running, and you will see the splash screen and then the Welcome to Android Studio screen as you might remember from Chapter 2. In the lower right of the welcome screen, you should see a cog icon and the menu option Configure, which you should click to reveal a range of configuration options as shown in Figure 3-1.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig1_HTML.jpg
Figure 3-1

The Configuration menu from the Welcome to Android Studio screen

You will see that the very first option on the list of configuration items presented is the AVD Manager option. Click this option, and the AVD Manager will start after a few seconds, and you should be presented with the introductory Android Virtual Device Manager screen shown in Figure 3-2.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig2_HTML.jpg
Figure 3-2

The Android Virtual Device Manager welcome screen

In the middle of the screen, you should see the button as shown in Figure 3-2 that reads + Create Virtual Device.... Go ahead and click that button to start the AVD creation process. You will then see the Virtual Device Configuration hardware selection screen, as shown in Figure 3-3.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig3_HTML.jpg
Figure 3-3

The Select Hardware option for new AVD creation

There is a lot going on in the hardware selection screen, but don’t feel overwhelmed. The multitude of options here convey the variables you will find in devices in the real world, so it really isn’t surprising. Let’s step through the areas one by one so you begin to feel at home with the AVD Manager and creating and using AVDs.

Starting on the left-hand side of the hardware selection screen, the Category list provides a grouping of device emulators based on form factor and usage pattern. You should see at least the five normal options shown in Figure 3-3, TV, Phone, Wear OS (formerly Android Wear), Tablet, and Automotive. Feel free to click through each of these to see how the device list (middle of the screen) and dimension detail window change, but when you’re done, choose Phone as the Category. With Phone selected, you should then see the original list of prepackaged emulated devices originally shown in Figure 3-3.

At this point, we won’t just race ahead to choose one of the first devices shown as the basis for our AVD. Instead, spend a moment to scroll through the list, and take note of a few data points that will resurface later in the book and will gradually make more sense and have more impact on your application design.

From the upper end of the list of device definitions, you will see makes and models of smartphones and brands, some of which might be very familiar. The various Pixel options, like Pixel 3, Pixel 2, and so on, and AVD images emulate as near as possible the real, physical devices that bear those names. Similarly, Nexus 6, Nexus 5, and so on are virtual devices that mimic the physical characteristics of their namesakes, whether it is on-board storage, working memory, screen resolution, or other capabilities. Before you scroll to see the rest of the list, take a look at the values shown in the Resolution and Density columns. You’ll see measurements for both, expressed in pixel layout for Resolution (e.g., 1080 × 1920 for the Pixel 2 AVD) and dots per inch, or dpi, for Density (again, 420 dpi for Pixel 2). You might be familiar with resolution and density measures for laptop or desktop screens and not give a second thought to the values you see here. But it is worth comparing these to the other AVDs in the list.

If you scroll further toward the bottom of the list, you will start to see a range of more cryptic device names, as shown in Figure 3-4.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig4_HTML.jpg
Figure 3-4

Further AVD templates available to you

These devices don’t have any brand names associated with them, but they do possess some indicators of what they offer, through using the abbreviations commonly associated with various screen sizes and resolutions. We will encounter these terms throughout this book, so for now you can bookmark names like QVGA, WQVGA, mdpi, hdpi, and so on and not labor over their meaning.

As if all of those current and historic options weren’t enough, you’ll see two buttons below the device definition list that allow for specifying your own custom virtual device profile and for importing a profile from another source. For our purposes, these options won’t be needed, but you can appreciate the value they offer – in particular for those of you who might eventually want to design applications targeting very specific, atypical devices.

We will revisit the concepts and principles of Android device resolution and density in Chapters 9, 10, and 11 when we delve into the depths of user interface design. For now, you can scroll back to the top of the device definition list and choose the Pixel 2 pre-configured device definition. Click the Next button, and you should see the System Image selection screen shown in Figure 3-5.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig5_HTML.jpg
Figure 3-5

The AVD System Image selection screen in AVD Manager

Choosing a system image can be considered the complementary step to your earlier choice of device definition. Whereas your device choice selected the hardware aspects of your AVD, the system image determines the key software aspects: Android API/SDK level and ABI, which is basically a decision of which chip architecture to emulate in software, Intel’s x86 or one of the Arm-based architectures, and which release of Android these pieces most closely match.

Android Software Development Kit: A Second Look

In Chapter 2 I introduced the term SDK, or Software Development Kit. While it’s easy to parse that phrase and think “Great, a kit to help me develop software,” it’s worth reviewing what the Android SDK really offers. First and foremost, the Android SDK is a set of software libraries, which are the fundamental tools needed to access the capabilities and power of any Android smartphone and its operating system. You can think of the SDK as the lever that lets you bring all of the power and capabilities Google has built into Android to bear in your own application, without needing to build everything from the ground up.

The Android SDKs – and there are successive versions released for every version of Android – provide the connection to Android Studio that lets you easily invoke Android behavior; build tools that let you turn your code into a working Android program; platform tools that let you manage applications that are still in development and running in “draft” form, including “adb,” the Android Debug Bridge, for controlling behavior on an emulator or real device from still-in-development code; and more. Oh, and the SDK provides the emulator framework and device emulation itself!

Depending on whether you have ever previously used a version of Android Studio on the computer you’ve chosen to use or have stepped through this wizard before, you will see the listed release names like “R” or “Oreo” with or without a download link next to the name. In short, if the system image is already available on your machine, it won’t show a download link. If it is yet to be used on your machine, the download link will show, and you can click it straight from the system image stage to fetch the relevant system image.

You will need to have at least one system image for your AVDs to use, so if all you see are system image names accompanied by download links, you should choose to download the latest one. In the example shown in Figure 3-5, this would be the Android “R” system image. Selecting the download will trigger a license acceptance screen, shown in Figure 3-6.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig6_HTML.jpg
Figure 3-6

An example license acceptance screen for AVD system images

I am not a lawyer, and I certainly don’t play one on TV! More seriously, that means I can’t advise you what the text of the license means or implies. If you are at all worried, seek legal counsel. But from a layperson’s perspective, the open source licenses used for Android system images are generally nothing to lose sleep over. I will assume you accept the text shown and, having clicked the Next button, are now staring at the Android Virtual Device (AVD) configuration verification screen shown in Figure 3-7.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig7_HTML.jpg
Figure 3-7

The Android Virtual Device (AVD) configuration verification screen

Use this screen to check you are happy with the configuration of your new AVD and, most importantly, to give it a memorable name. You can call your AVDs anything you like – there’s no need to keep model or make names that might have been inherited from one of the pre-configured system images, though it can help to keep it as part of the name as a quick reminder of the features of your emulated device. Choose a name, and then click the Finish button, to head to the AVD Manager home screen, as shown in Figure 3-8.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig8_HTML.jpg
Figure 3-8

The populated AVD Manager home screen

You should now see your newly created AVD in the list of available emulated devices. That’s it for creating your first Android Virtual Device – you are now ready to get your own application written and running on it!

Creating Your First Android Application, Already!

You have all the prerequisites in place to get started with your first Android application. There is still a great deal to learn, but you already have the key pieces at hand, including Android Studio and a newly created Android Virtual Device ready to try out whatever you write. Hopefully this ready-to-go status isn’t surprising to you. I outlined some of the benefits of IDEs in Chapter 2, and you’re about to experience this directly in the area of setting up the scaffolding and framework of a new application.

Without any further suspense, let’s get started. If you have followed along with the earlier steps in this chapter, completing the creation of an AVD, you will likely be back at the Android Studio home screen you saw earlier in the chapter, in Figure 3-1. From that home screen, choose the Start a new Android Studio project option at the top of the screen, and you will shortly see the first screen of the Create New Project wizard.

If, for whatever reason, you don’t have that home screen visible or have restarted Android Studio and it doesn’t show the home screen wizard, you might instead be looking at an empty Android Studio screen or one that has loaded a pre-existing project, as shown in Figure 3-9.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig9_HTML.jpg
Figure 3-9

Android Studio as it appears when the home screen disappears

Don’t panic! You can also initiate a new project from here, but opening the File menu and choosing NewNew Project. This will also launch the Create New Project wizard. Regardless of the path you’ve taken, you should shortly see the wizard as shown in Figure 3-10
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig10_HTML.jpg
Figure 3-10

The Create New Project wizard in Android Studio

The first page of the wizard is already prompting you to make some choices about what kind of application you would like to build. Across the top of the screen, you will see device categories, such as Phone and Tablet, Wear OS, TV, and so on. At this moment, we will stick with the Phone and Tablet wizard option. Looking at the icons displayed beneath Phone and Tablet, you are likely scratching your head, perplexed as to what terms like activity, fragment, and so forth mean. Fear not. You’ll soon master these. At this stage, you can treat this screen as Android Studio asking you exactly how much bootstrapping you want for your new application and what ready-made pieces you would like it to put in place on your behalf. For instance, if you anticipate making an application reliant on maps and navigation capabilities, the Google Maps Activity template adds in a bunch of mapping, GPS, and location support options ready-made for developers. Other options on this screen similarly pull in other goodies, such as Ad library support for the Google AdMob Ads Activity.

We are going to start with a very plain, vanilla Android application, creating variants of this simple application showing each feature discussed as we work through the coming chapters. So for now, you can choose the Empty Activity option. Don’t let the word Empty fool you, as the Empty Activity option still deploys much of the boilerplate and basic project structure you need for your application. With Empty Activity selected, click the Next button, and you should see the Configure Your Project screen, as shown in Figure 3-11.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig11_HTML.jpg
Figure 3-11

The Configure Your Project screen in Android Studio

The options shown on this screen are all that stand between you and adding your own code and touches to your application. For your current MyFirstApp project, you will want to specify the following settings:

Name: This should be a meaningful name for your application. It’s the title that will appear on-screen when running the app, it’s the caption that will appear under the app’s icon from Android launcher screens, and should you even publish this app in the Google Play store or elsewhere, it’s the name that will appear there. For our purposes, enter MyFirstApp as the name.

Package name: In a world with tens of thousands of developers creating hundreds of thousands of applications for Android, how do you ensure no two apps conflict when it comes to naming? Rather than enforce unique names (though places like Google Play do have some restrictions in this regard), Android leverages the fundamental mechanism of package names derived from the Java standard. We will talk more about Java package naming in Chapter 7, so for now you can use a package name derived from one of my own domain names – org.beginningandroid.myfirstapp.

Save location: The save location is the folder on disk where the entire hierarchy of code for this application will be stored. This will include menu subfolders, holding contents like source code, configuration files, images, video, and more, depending on how sophisticated we make this application. To begin with, the space used by a new project will be under 1 MB. But this can grow quickly, so it’s best to choose a location on disk that you know has ample spare space. If you’re happy with the default, you can accept it – a directory named AndroidStudioProject/MyFirstApp under your user’s home directory on your operating system.

Language: Open the pick list you see, and you are presented with two options: Kotlin or Java. Kotlin is a newer addition to the family of languages that Android supports for authoring applications. Java is the first and still by a massive margin the largest used and most popular language for Android development. Choose Java as the language for MyFirstApp.

Minimum SDK: Here is where our discussion of Android versions, Android Studio versions, and Android SDK versions from Chapter 2 and this chapter starts to pay off. Your selection here will dictate what version of the SDK is used for this application and therefore to a large degree what devices it will be compatible with from the history of Android devices. Newer releases of the Android SDK provide support for newer features, whereas older releases are more likely to be supported on older – and therefore more – devices. You will see the additional text next to your selection that indicates what percentage of activated Google devices in use throughout the world would support the SDK version of your choice. There is no perfect answer to the best trade-off between new features and broad support. For now, our initial application is not going to use any cutting-edge features from the latest release of the Android SDK, so you can go with the default, choosing API 16, which was first released to coincide with the Android 4.1 Jelly Bean release from several years ago. You can scroll through the list to choose another SDK release if you wish. If your chosen SDK version is not currently installed on your computer, it will be downloaded along with the steps taken to complete setting up this initial application – be sure to account for the 100+ MB of disk space used for each SDK version.

Use legacy android.support libraries: Over the years, Google has tried a number of approaches to deal with the version fragmentation seen in use by active Android devices. One approach was (and still is) to use an additional support library not tied to any one particular SDK version and have applications utilize this support library. The subtlety was that Google was much more able to push updates for the support library, as compared to the Android installation of any particular device. We will talk more about this in coming chapters when we discuss androidx and Jetpack. For now, you can leave this setting at the default of unchecked, meaning we won’t pull in support for these libraries.

You are now one step away from a runnable Android application. Click the Finish button, and Android Studio will spring to life, generating the structure and scaffolding for your new Android application and its project folders. After a short time, you should eventually see the full project and the full developer interface for Android Studio appear, as shown in Figure 3-12.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig12_HTML.jpg
Figure 3-12

Android Studio showing the MyFirstApp project open for editing

Getting Your First Code Written

If you review the layout of your new project as shown in Figure 3-12, you will see a folder/directory hierarchy with all manner of names, such as manifests, java , res, and more. We are going to explore the full project layout, the directories you see, the starter files that populate them, and the pieces you build in the very next chapter.

Right now, in the interests of getting you a working application with your own personal touch, we are going to skip the explanations of those items and dive straight into editing your first application component. Use the Project hierarchy view you see on the left of the Android Studio layout, and click down through the res folder and then the layout subfolder. You should see a file-like entry named activity_main.xml (because these are, actually, files!). Double-click the activity_main.xml file, and it will open in the editor view of Android Studio, as you can see in Figure 3-13.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig13_HTML.jpg
Figure 3-13

Opening your first source file in Android Studio

Looking at screenshots of code is tedious, so let’s look at the content of the activity_main.xml file. Your file should look like Listing 3-1.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Listing 3-1

The contents of the activity_main.xml file in a new Android Studio project

There are a few different parts of this file that will interest us in the future, but for now we are only interested in one part of the code here, which you see in bold. You will note that about halfway through the file is the line
android:text="Hello World!"

Go ahead and edit the string within the double quotes, so instead of reading "Hello World!", it reads something like "Hello Android!" or whatever takes your fancy. Once you are done editing this file, save your changes. You’ve just made your first custom edit to an Android application!

Getting Ready to Run Your Application

You are now ready to have Android Studio run your new application inside the AVD emulator you created earlier in the chapter. In order for Android Studio to do this, it needs to know what your particular preferences are when you ask it to run the application. For example, do you just want it to run normally, so you can interact with it, or do you want it to run in a debugging mode or some other way that lets you carefully examine what is happening in the code or to the interactions between your application and the Android host device, other APIs you may be calling, or external services such as cloud-based APIs?

Android Studio controls these alternative approaches to running your applications through what are known as run configurations. These are preset instructions on exactly what you mean by “run” when running an application.

You can trigger Android Studio to walk you through setting up your first run configuration by simply trying to run your application right now. Open the Run menu, and choose the Run... option. Without any pre-existing run configurations in place, Android Studio will now prompt you to edit a configuration, as shown in Figure 3-14.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig14_HTML.jpg
Figure 3-14

The prompt to edit your first run configuration

Note

You can always directly edit run configurations without forcibly running an application, by choosing the Edit Configurations… option from the Run menu.

Whichever way you’ve triggered the creation of your first run configuration, you will see the Run/Debug Configurations screen displayed. The text on that screen will indicate to click the “+” button to add a new configuration, and you should do that. You will see the list of options shown in Figure 3-15.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig15_HTML.jpg
Figure 3-15

Selecting a new base run configuration

Choose the Android App option at the top of the list presented, and you will then see the detailed configuration screen as shown in Figure 3-16.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig16_HTML.jpg
Figure 3-16

Detailed configuration for a new run configuration

There are two settings you will need to make. The first setting is to provide your run configuration with a memorable name. I am going to suggest you use the name Run Config 1. Next, you need to nominate which module of code the run configuration should initiate when running your application. The only option in the list is app, which is fortunate, as that’s the option you want. You can see both of these settings in Figure 3-16.

Click the Apply and OK buttons to save away your configuration.

Installing (Additional) SDK Packages

Depending on how you choose your application’s minimum SDK setting earlier in this chapter and the options you selected when first installing Android Studio, you might not have the relevant SDK bundle installed on your machine for Android Studio to use in building your application. You can spot this easily, as you’re default view in Android Studio includes the current build status in the lower left of the screen.

If you look at the “Build: Sync” area and see an error or warning worded as follows, you likely need to download an SDK package to match the one selected for your project:
License for package Android SDK Platform 29 not accepted
or
Module 'app': platform 'android-29' not found
The version number mentioned in the warnings or errors might differ in your installation. Whatever the version, this is easily fixed by invoking the SDK Manager feature (yet another piece of integration offered by the IDE). From the Tools menu of Android Studio, choose the SDK Manager option, and you should see the SDK Manager appear as shown in Figure 3-17.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig17_HTML.jpg
Figure 3-17

The Android SDK Manager

To add the SDK needed for your project, simply check the box next to the relevant version – in my case, that is “Android 10.0 (Q),” which equates to API level 29 or, in other words, version 29 of the Android SDK. Click the Apply button, and the SDK Manager will then trigger the download of this version of the SDK. If you sit back and think about it for a moment, you will realize that as you build more and more applications and potentially choose different target SDK versions for them, you will likely end up with quite a few different versions of the Android SDK installed on your machine, and together, these will take a considerable amount of disk space. We’ll revisit this topic in Chapter 6, when we look in depth at your overall developer system setup.

Once the download of any needed Android SDK version is complete, you should see the status as shown in Figure 3-18.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig18_HTML.jpg
Figure 3-18

The Android SDK Manager indicating successful download and install of a new SDK version

At this point, you will need to have Android Studio refresh the configuration for the integrated Gradle build tool so it realizes the new SDK is in place. Android Studio can take all the necessary steps to do this – so don’t panic at this point if you know nothing about Gradle as a build tool. Simply open the File menu, and select the option that reads Sync Project with Gradle Files.

When this sync activity completes, in the Build window in the lower left of the screen, you should see the previous warnings and errors are now gone, and the only message present should read MyFirstApp successful at some-date-and-time.

Running Your Application

With a completed setup in Android Studio matching the needs of your application and Gradle in sync and ready to build your application, your run configuration should now be able to actually run your new application. Go ahead and choose Run from the Run menu, or directly choose Run 'Run Config 1' to skip the run configuration selection step.

A bunch of actions will now happen automatically, but they can take a little time – up to a few minutes depending on the capabilities of your computer. First, Gradle will be invoked to build your application. We will cover this process in more detail in later chapters, but for now what you need to know is that Gradle is pulling together all of the code you wrote, the libraries referenced by your application, the relevant Android SDK, and other plumbing and generating a bundle ready to deploy as your application. This is known as an Android Package, or APK.

Next, Android Studio invokes your AVD, and after the time it takes for that emulator to start, it copies over the APK built by Gradle. Based on your run configuration, Android Studio knows that you want to run the app module, in effect triggering your new MyFirstApp application to run in the AVD, just as if you’d pressed its icon in the Android launcher window.

Your app will run, and your immortal words “Hello Android!” (or whatever you chose) should appear within an app screen titled MyFirstApp, just as you see in Figure 3-19.
../images/499629_1_En_3_Chapter/499629_1_En_3_Fig19_HTML.jpg
Figure 3-19

Your running MyFirstApp Android application within your AVD

That’s it! You have written and run your first Android application. Well done. Take a deep breath, because in Chapter 4 we are going to dive under the hood and examine everything that Android Studio has just built for you in great detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.178.207