Tải bản đầy đủ (.pdf) (469 trang)

Learn Android Studio

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.61 MB, 469 trang )

Learn

Android Studio
Build Android Apps Quickly and Effectively
Adam Gerber | Clifton Craig

www.it-ebooks.info


For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.

www.it-ebooks.info


Contents at a Glance
About the Authors��������������������������������������������������������������������������������������������������xvii
About the Technical Reviewer��������������������������������������������������������������������������������xix
Acknowledgments��������������������������������������������������������������������������������������������������xxi
Introduction����������������������������������������������������������������������������������������������������������xxiii
■■Chapter 1: Introducing Android Studio������������������������������������������������������������������ 1
■■Chapter 2: Navigating Android Studio ���������������������������������������������������������������� 27
■■Chapter 3: Programming in Android Studio�������������������������������������������������������� 45
■■Chapter 4: Refactoring Code�������������������������������������������������������������������������������� 69
■■Chapter 5: Reminders Lab: Part 1������������������������������������������������������������������������ 89
■■Chapter 6: Reminders Lab: Part 2���������������������������������������������������������������������� 121
■■Chapter 7: Introducing Git��������������������������������������������������������������������������������� 145
■■Chapter 8: Designing Layouts���������������������������������������������������������������������������� 189
■■Chapter 9: Currencies Lab: Part 1���������������������������������������������������������������������� 241
■■Chapter 10: Currencies Lab: Part 2�������������������������������������������������������������������� 267


■■Chapter 11: Testing and Analyzing�������������������������������������������������������������������� 297
■■Chapter 12: Debugging�������������������������������������������������������������������������������������� 313

v

www.it-ebooks.info


vi

Contents at a Glance

■■Chapter 13: Gradle��������������������������������������������������������������������������������������������� 339
■■Chapter 14: More SDK Tools������������������������������������������������������������������������������ 371
■■Chapter 15: Android Wear Lab��������������������������������������������������������������������������� 407
■■Chapter 16: Customizing Android Studio���������������������������������������������������������� 431
Index��������������������������������������������������������������������������������������������������������������������� 445

www.it-ebooks.info


Introduction
Around 530 million years ago, during an age geologists call the Cambrian explosion, a
wide variety of species including all the phyla that exist today burst into existence within as
little as 10 million years—a mere flash in geological time. Scientists continue to marvel at
this phenomenon, and Darwin himself suggested that the Cambrian explosion happened
so swiftly that it might well cast doubt on his theory of natural selection. Today we are
experiencing the technological equivalent of the Cambrian explosion. The U.S. Bureau of Labor
Statistics predicts that a person graduating high school today will have 11 jobs in her lifetime,
and much of this career transience can be attributed to the pace of technological change.i

Technology begets more technology, and new technologies proliferate with ever-increasing
speed. Some of these new technologies will survive beyond a few years, but most will
not. There is little worse than investing time and energy in acquiring a new skill that is
obsolete on arrival or whose utility is short-lived. We wrote this book because we believe
that the tools and technologies covered herein will endure and that they are well worth your
investment.

Small Is Beautiful
Moore’s Law, which states that processing power doubles approximately every 18 months,
is relentless. Over the past few years, laptop computers have achieved performance
parity with their larger desktop cousins. Laptops and notepad computers accounted for
81 percent of PC sales in 2014ii, and sales are projected to increase at the expense of
desktop sales, which are conversely projected to decline. The brilliance of this trend is that
no individual or group has the power to arrest or reverse it—such is the power of economic
forces, which are the result of aggregate individual choices. Laptops will be the tool of
choice for knowledge workers for roughly the next ten years. However, a silent revolution is

i

/>Source: Forrester Research eReader Forecast, 2010 to 2015 (US).

ii

xxiii

www.it-ebooks.info


xxiv


Introduction

currently afoot that will soon topple the almighty laptop. Around 2025, or possibly sooner,
our smartphones will achieve performance parity with our laptops—which is to say that
the larger form-factor will no longer afford any performance advantages over the smaller.
Ultimately, our mobile computer (MC) will be used for the vast majority of computing
applications, even those applications that you and I can only imagine doing on our laptops
today. This revolution is just as predictable and just as certain as the one that overthrew the
desktop. In the meantime, you can expect your MC (in other words, your smartphone or
tablet) to start functioning in ways that resemble your laptop, including the ability to dock to
peripherals such as keyboards, monitors, and mice.
The personal computer (PC) age is coming to a close, but the MC age will actually be far
more personal. Soon a whole host of new wearable devices such as watches, glasses, and
shoes will be available. We envision a day in the not-too-distant future in which we will wear
our computers on our bodies and dock to monitors, keyboards, and mice wherever those
peripherals are available. This will truly be an age of personal computing, though we are not
likely to call it that.

Android Advantages
If you aspire to become an Android developer, you’ve made an excellent choice. Billions of
people in the developing world will be coming online in the next decade. For most of these
people, their first computers will be smartphones, and most of these smartphones will be
powered by Androidiii. There’s good reason for our optimism and already a lot of historical
data from which we can extrapolate. Gartner Group projects that 1.25billion Android devices
will be sold in 2015iv. At the time of this writing, Android accounts for over three-quarters
of the Chinese market alonev, and Chinese consumers are prepared to make staggeringly
large investments in mobile devices, some spending as much as 70 percent of their monthly
salary on a new mobile device because connectivity is a prerequisite for participation in the
global economy.vi China is the largest market in sheer volume, but we can observe similar
trends across the developing world. Furthermore, because the Android OS is open source

and free, it is almost always the first choice among manufacturers of TV consoles, gaming
systems, augmented reality systems, and other electronic devices, of which there are many.
Android will continue to consolidate its dominant global market position for several
reasons. Android’s modular architecture allows for a wide variety of configurations and
customizations. All the core applications that ship standard with Android devices are
interchangeable with any number of third-party applications, and that includes applications

iii

/>iv
www.bbc.co.uk/news/technology-25632430.
v
Report: Windows Phone overtakes iOS in Italy and makes progress in Europe - The Next Web.
(n.d.). Retrieved from />vi
Report: Windows Phone overtakes iOS in Italy and makes progress in Europe - The Next Web.
(n.d.). Retrieved from />
www.it-ebooks.info


Introduction

xxv

like the phone dialer, the e-mail client, the browser, and even the OS navigator. Android
devices are available in an amazing variety of shapes and functions. There are Android
augmented reality glasses, Android game consoles (of which Ouya is the most notable),
Android watches, Android tablets of every conceivable size, and, of course, Android
smartphones.
Android’s core technologies compare favorably to those of its principal competitors.
Android’s inclusive and open source charter has attracted a large and impressive collection

of allies, including Samsung, which is among the most innovative companies in the world.
A freevii and customizable operating system means that Android device manufacturers
can focus on bringing products to market with unrivaled value, and the highly competitive
Android device market continues to produce inexpensive, high-quality, and architecturally
open devices.

Android Studio Is Revolutionary
As a knowledge worker, your choice of tools can mean the difference between struggling
and thriving. We’re always searching for tools that increase productivity and automate work.
Certain tools have benefits that are so apparent that one adopts them immediately. Android
Studio is one such tool.
We were introduced to Android Studio just a few days after its prerelease at Google I/O
in 2013. Prior to that time, we had both been using Android Developer Tools (ADT) both
professionally and in the classroom. ADT is an Android development environment built upon
the opensource integrated development environment (IDE) called Eclipse. While Android
Studio was still in early prerelease, we both began to use Android Studio professionally.
Android Studio is a collaboration between JetBrains and Google. Android Studio is built atop
JetBrain’s IntelliJ, and so its functionality is a superset of IntelliJ. Most anything you can do
with IntelliJ, you can also do in Android Studio. Android Studio is revolutionary because it
streamlines the Android development process and makes Android development far more
accessible than it has previously beenviii. Android Studio is now the official IDE for Android.

The Android Tools Ecosystem
Android is a technology platform with its own ecosystem of tools to support it. After Android
Studio, the next most important tool in the Android ecosystem is Git. Git is a distributed
source-control tool that is quickly becoming the standard not only for mobile development,
but for software engineering in general. We have never worked on a mobile development
project that does not use Git for version control. Git could very well be the subject of another

It’s important to note that while Google has forgone license fees from Android, mobile

technology proliferation in general tends to buoy Google’s advertising revenue.
viii
Developing Android apps requires a solid understanding of Java. Nothing as powerful as Android
is easy, but using Android Studio will make the task of developing Android apps easier.
vii

www.it-ebooks.info


xxvi

Introduction

book, but fortunately you needn’t understand all of Git’s functionality to be proficient at using
it. Android Studio has an excellent, full-featured, and integrated Git tool with an impressive
GUI interface. In this book, we cover the features you need to know to be an effective
Git user and then point you to resources for additional study if you wish to deepen your
knowledge of this indispensible tool.
Another important tool in the Android ecosystem is Gradle. Gradle is a build tool similar to
Ant and Maven that allows you to manage libraries and library projects, run instrumentation
tests, and create conditional builds. Android Studio does a good job of managing libraries
all on its own, but Gradle makes this task easy and portable. As with Git, Gradle is fully
integrated into Android Studio, which ships with an impressive array of views that allow the
user to inspect Gradle files graphically and examine the output of a Gradle build process.

Android and Java
If you attempt to develop Android apps in Android Studio without first having a good
understanding of Java, you will be frustrated. Java is an extremely useful and popular
programming language for many reasons. Perhaps the most important reason for Java’s
popularity is that Java is memory managed. Memory managed means that the programmer

does not need to be concerned with deallocating memory off the heap, nor with worrying
about memory leaks. Programmers developing in a memory-managed environment tend
to be more productive, and their programs tend to have fewer runtime errors. Like Java,
Android is a memory-managed programming environment. Managing memory turns out to
be such a good idea that both Microsoft and Apple have adopted this model for their mobile
development platforms.ix

Switching from ADT/Eclipse
If you are an experienced Android developer and are used to programming with ADT, you
are in for a pleasant surprise. Thankfully, all the SDK tools such as DDMS and Hierarchy
Viewer are still available, and you will find them easily accessible from within Android Studio.
If you’re an ADT user, you probably find yourself continuously cleaning and rebuilding your
projects in order to synchronize your resources with your source code (the dreaded R.java
synchronization error). In the months that we have been using Android Studio, we have
never been troubled with this problem. If you’re an experienced ADT user, then in order
to get up to speed with Android Studio, you will need to learn a few keyboard shortcuts,
familiarize yourself with Gradle, and reorient yourself to Android Studio’s presentation logic.
Altogether, this is a small price to pay for the power and pleasure of Android Studio.

Xcode, which is the IDE for developing iOS apps, recently included a feature called Automatic
Reference Counting whereby the compiler generates code that manages memory automatically.
Microsoft C# is a memory-managed programming environment inspired by Java.

ix

www.it-ebooks.info


Introduction


xxvii

Conventions Used in This Book
Android Studio is remarkably consistent across operating systems. In fact, the user
interfaces on Windows and Linux are almost identical. However, Mac OS users will find that
some of the locations of their menus and some keyboard shortcuts are different. We use
Windows when covering subjects that require OS navigation. However, when we indicate a
keyboard shortcut, we include both the Windows-Linux and Mac shortcuts separated by a
pipe (for example, Ctrl+K | Cmd+K). When appropriate, we include notes, links, and other
resources for Mac users.

www.it-ebooks.info


Chapter

1

Introducing Android Studio
This chapter walks you through installing and setting up your development environment
so you can follow the examples and labs in this book. First, you will install an essential
prerequisite component called the Java Development Kit (JDK). Then you will download
and install Android Studio as well as the Android Software Development Kit (SDK), which is
a suite of software tools required to build Android apps. We will show you how to use the
New Project Wizard to create a simple project called HelloWorld. Last, we will show you how
to establish a connection to both an Android Virtual Device (AVD) and a physical Android
device. By the end of this chapter, you will have everything you need to start developing
apps in Android Studio.

Installing the Java Development Kit on Windows

This section pertains to Windows users. If you’re a Mac user, skip ahead to the section titled
“Installing the Java Development Kit on Mac.” Android Studio uses the Java tool chain to
build, so you need to make sure that you have the Java Development Kit (JDK) installed on
your computer before you start using Android Studio. It’s quite possible that you already
have the JDK installed on your computer, particularly if you’re a seasoned Android or Java
developer. If you already have the JDK installed on your computer, and you’re running JDK
version 1.6 or higher, then you can skip this section. However, you may want to download,
install, and configure the latest JDK anyway. You can download the JDK from the following
Oracle site:

www.oracle.com/technetwork/java/javase/downloads/index.html


When you land on this page, click the Java Download button, shown in Figure 1-1.

1

www.it-ebooks.info


2

CHAPTER 1: Introducing Android Studio

Figure 1-1.  The Java Download button on the Java Downloads page

Downloading the JDK on Windows
The next step in the installation, shown in Figure 1-2, requires that you accept a license
agreement by clicking the Accept License Agreement radio button. Then you must choose
the appropriate JDK for your operating system. If you’re running Windows 7 or Windows 8,

you should click the file link to the right of the Windows x64 label, also shown in Figure 1-2.
Oracle makes frequent release updates to the JDK. By the time this book goes to press, a
newer version of the JDK will almost certainly be available, so please be sure to download
the latest version. Wait for the installation file to download. This file is usually around 125MB,
so the download shouldn’t take long.

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

Figure 1-2.  Accept the license agreement and click the appropriate link for Windows

Executing the JDK Wizard on Windows
Before you install the JDK, create a directory in the root of your C: drive called Java. The
name of this directory is arbitrary, though we call it Java because many of the tools we are
going to install here are related to Java, including the JDK, Android Studio, and the Android
SDK. Consistently installing the tools related to Android Studio in the C:\Java directory also
keeps your development environment organized.
Navigate to the location where your browser downloaded the installation file and execute
that file by double-clicking it. Once the installation begins, you will be presented with the
Installation Wizard, shown in Figure 1-3. In Windows, the JDK installer defaults to
C:\Program Files\Java\. To change the installation directory location, click the Change
button. We recommend installing your JDK in the C:\Java directory because it contains no
spaces in the path name and it’s easy to remember. See Figure 1-4.

www.it-ebooks.info

3



4

CHAPTER 1: Introducing Android Studio

Figure 1-3.  Installation Wizard for the JDK on Windows

Figure 1-4.  Select the JDK installation directory

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

Make a note of where you are installing your JDK. Follow the prompts until the installation is
complete. If prompted to install the Java Runtime Edition (JRE), choose the same directory
where you installed the JDK.

Configuring Environmental Variables on Windows
This section shows you how to configure Windows so that the JDK is found by Android
Studio. On a computer running Windows, hold down the Windows key and press the Pause
key to open the System window. Click the Advanced System Settings option, shown in
Figure 1-5.

Figure 1-5.  Windows System window

www.it-ebooks.info

5



6

CHAPTER 1: Introducing Android Studio

Click the Environmental Variables button, shown in Figure 1-6. In the System Variables list
along the bottom, shown in Figure 1-7, navigate to the JAVA_HOME item. If the JAVA_HOME item
does not exist, click New to create it. Otherwise, click Edit.

Figure 1-6.  System properties

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

Figure 1-7.  Environmental variables

Clicking either New or Edit displays a dialog box similar to Figure 1-8. Be sure to type
JAVA_HOME in the Variable Name field. In the Variable Value field, type the location where you
installed the JDK earlier (less any trailing slashes), as shown in Figure 1-4. Now click OK.

Figure 1-8.  Edit the JAVA_HOME environmental variable

www.it-ebooks.info

7


8


CHAPTER 1: Introducing Android Studio

Just as you did with the JAVA_HOME environmental variable, you will need to edit the PATH
environmental variable. See Figure 1-9. Place your cursor at the end of the Variable Value
field and type the following:
;%JAVA_HOME%\bin

Figure 1-9.  Edit the PATH environmental variable

Now click OK, OK, OK to accept these changes and back out of the system properties.
To test that the new JDK has been installed properly, pull up a command line by clicking the
Start button, typing cmd, and then pressing Enter.
In the command-line window, issue the following command and press Enter:

java –version


If you get a response like the one shown in Figure 1-10, congratulations. You just installed
the JDK properly.

Figure 1-10.  Confirm the proper JDK installation

Installing the Java Development Kit on Mac
The first two steps in installing the JDK for Mac and Windows are identical. Point your
browser to the following site:

www.oracle.com/technetwork/java/javase/downloads/index.html



When you land on this page, click the Java Download button, shown in Figure 1-11.

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

Figure 1-11.  The Java Download button on the Java Downloads page

Downloading the JDK on Mac
Accept the license agreement, shown in Figure 1-12, by clicking the Accept License
Agreement radio button. Then you must choose the appropriate JDK for your operating
system. If you’re running a 64-bit version of OS X, you should click the file link to the
right of the Mac OS X64 label, also shown in Figure 1-12. Oracle makes frequent release
updates to the JDK. By the time this book goes to press, a newer version of the JDK will
almost certainly be available, so please be sure to download the latest version. Wait for the
installation file to download.

www.it-ebooks.info

9


10

CHAPTER 1: Introducing Android Studio

Figure 1-12.  Accept the license agreement and click the appropriate link for Mac

Executing the JDK Wizard on Mac

Double-click the .dmg file to execute it. Now click the .pkg file to begin the wizard and click
Continue as required, as shown in Figures 1-13 through 1-15.

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

Figure 1-13.  JDK 8 Update 25.pkg

Figure 1-14.  Installation Wizard

www.it-ebooks.info

11


12

CHAPTER 1: Introducing Android Studio

Figure 1-15.  Installation success

Configuring the JDK Version on Mac
To configure your Mac so that the proper JDK is found by Android Studio, open a Finder
window and choose Applications ➤ Utilities. From there, open Java Preferences and, as
instructed, drag the new version to the top of the list so it is recognized as the preferred
version.

Installing Android Studio

Before you begin downloading Android Studio, create a labs parent directory for the labs
you will create in this book. We use C:\androidBook\ as our labs’ parent directory throughout
the book, but you may choose or create whatever directory you see fit. For that reason, we
simply call it the labs parent directory.
Downloading Android Studio is straightforward. Point your browser to this site:
developer.android.com/sdk/installing/studio.html

Now click the large green Download Android Studio for your OS button, shown in Figure 1-16.
Next, select the check box labeled I Have Read and Agree with the Above Terms and
Conditions. Click Download Android Studio for your OS again, and your installation file
should begin downloading. Once the download is complete, execute the file you just
downloaded.

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

13

Figure 1-16.  Download Android Studio

After the Installation Wizard begins, move through its screens by clicking the Next buttons
until you reach the Choose Components screen. There, select all the component check
boxes, shown in Figure 1-17. Then click Next. Agree to the terms and conditions once again.
When you reach the Configuration Settings: Install Locations screen, shown in Figure 1-18,
select the locations for Android Studio and the Android SDK. To be consistent, we chose to
install Android Studio in C:\Java\astudio\ and the Android SDK in C:\Java\asdk\.

Figure 1-17.  Choose components


www.it-ebooks.info


14

CHAPTER 1: Introducing Android Studio

Figure 1-18.  Select locations for Android Studio and the SDK

Click through several Next buttons as you install both Android Studio and the Android SDK.
You should eventually arrive at the Completing the Android Studio Setup screen, shown in
Figure 1-19. The Start Android Studio check box enables Android Studio to launch after you
click Finish. Make sure the check box is selected, and then go ahead and click Finish, and
Android Studio will launch. Please note that from here on out, you will need to navigate to
either the desktop icon or the Start menu to launch Android Studio.

Figure 1-19.  Completing the Android Studio setup

www.it-ebooks.info


CHAPTER 1: Introducing Android Studio

15

When Android Studio starts for the very first time, the Setup Wizard, shown in Figure 1-20,
will analyze your system looking for an existing JDK (such as the one you installed earlier),
as well as the location of the Android SDK. The Setup Wizard should download everything
you need to begin developing apps in Android Studio. Click the Finish button to dismiss the

Setup Wizard.

Figure 1-20.  Setup Wizard – Downloading Components

Creating Your First Project: HelloWorld
Once the Setup Wizard is complete, the Welcome to Android Studio dialog box appears,
shown in Figure 1-21. Click the Start a New Android Project option.

www.it-ebooks.info


16

CHAPTER 1: Introducing Android Studio

Figure 1-21.  Welcome to Android Studio

In the New Project wizard that appears (see Figure 1-22), type HelloWorld in the Application
Name field and type gerber.apress.com in the Company Domain field. Notice that the
package name is the reverse company domain plus the name of the project. Install your
HelloWorld project in the root of your labs parent directory. As mentioned earlier, we use
C:\androidBook\ if you’re running Windows. If you’re running Mac or Linux, your labs parent
directory name will not begin with a letter, but rather a forward slash.

www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×