Java® Programming for Android® Developers For Dummies®, 2nd Edition
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2017 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions
.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Java is a registered trademark of Oracle America, Inc. Android is a registered trademark of Google, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies
.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com
. For more information about Wiley products, visit www.wiley.com
.
Library of Congress Control Number: 2016954409
ISBN: 978-1-119-30108-0; 978-1-119-30109-7 (ebk); 978-1-119-30112-7 (ebk)
Android is everywhere. In mid-2016, Android runs on 65 percent of all smartphones in the United States, on 75 percent of all smartphones in EU5 countries, and on 77 percent of all smartphones in China.1 In a study that spans the Americas, Europe, Asia, and the Middle East, GlobalWebIndex reports that “Android is the most favored OS when it comes to tablets, being used by almost a fifth of internet users and leading iPad by 5 points.”2 More than 2.2 million apps are available for download at the Google Play store.3 And 9 million developers write code using Java, the language that powers Android devices.4
If you read this book in a public place (on a commuter train, at the beach, or on the dance floor at the Coyote Ugly saloon, for example), you can read proudly, with a chip on your shoulder and with your head held high. Android is hot stuff, and you're cool because you're reading about it.
You can attack this book in either of two ways: Go from cover to cover or poke around from one chapter to another. You can even do both (start at the beginning, and then jump to a section that particularly interests you). This book was designed so that the basic topics come first, and the more-involved topics follow them. But you may already be comfortable with some basics, or you may have specific goals that don't require you to know about certain topics.
In general, my advice is this:
Almost every technically themed book starts with a little typeface legend, and Java Programming for Android Developers For Dummies, 2nd Edition, is no exception. What follows is a brief explanation of the typefaces used in this book:
public void Anyname
which means that you type public void and then a name that you make up on your own. Words that you need to replace with your own words are set in italicized computerese.
Pick the first chapter or section that has material you don’t already know and start reading there. Of course, you may hate making decisions as much as I do. If so, here are some guidelines you can follow:
If you want to skip the sidebars and the paragraphs with Technical Stuff icons, please do. In fact, if you want to skip anything at all, feel free.
In this book, I make a few assumptions about you, the reader. If one of these assumptions is incorrect, you’re probably okay. If all these assumptions are incorrect … well, buy the book anyway.
I assume that you can navigate your computer’s common menus and dialog boxes. You don’t have to be a Windows, Macintosh, or Linux power user, but you should be able to start a program, find a file, put a file into a certain directory — that sort of thing. Much of the time, when you follow the instructions in this book, you’re typing code on the keyboard, not pointing and clicking the mouse.
On those occasions when you need to drag and drop, cut and paste, or plug and play, I guide you carefully through the steps. But your computer may be configured in any of several billion ways, and my instructions may not quite fit your special situation. When you reach one of these platform-specific tasks, try following the steps in this book. If the steps don’t quite fit, consult a book with instructions tailored to your system. If you can't find such a book, send me an email. (My address appears later in the Introduction.)
I make very few assumptions about your computer programming experience (or your lack of such experience). In writing this book, I’ve tried to do the impossible: make the book interesting for experienced programmers yet accessible to people with little or no programming experience. This means that I don’t assume any particular programming background on your part. If you’ve never created a loop or indexed an array, that’s okay.
On the other hand, if you’ve done these things (maybe in Visual Basic, COBOL, or C++), you’ll discover some interesting plot twists in Java. The creators of Java took the best ideas from object-oriented programming, streamlined them, reworked them, and reorganized them into a sleek, powerful way of thinking about problems. You’ll find many new, thought-provoking features in Java. As you find out about these features, many of them will seem quite natural to you. One way or another, you’ll feel good about using Java.
This book is divided into subsections, which are grouped into sections, which come together to make chapters, which are lumped, finally, into five parts (like one of those Russian matryoshka dolls). The parts of the book are described here.
Part 1 covers all the nuts and bolts. It introduces you to the major ideas behind Java and Android software development and walks you through the installation of the necessary software products. You also run a few simple Java and Android programs.
The instructions in these chapters cover both Windows and Macintosh computers. They cover many computer configurations, including some not-so-new operating system versions, 32-bit systems and 64-bit systems, and situations in which you already have some form of Java on your computer. But installing software is always tricky, and you might have a few hurdles to overcome. If you do, check the end of this chapter for ways to reach me (the author) and get some quick advice. (Yes, I answer emails, tweets, Facebook posts, and notes sent by carrier pigeons.)
Chapters 4 through 8 cover Java's basic building blocks. These chapters describe the things you need to know so that you can get your computer humming along.
If you’ve written programs in Visual Basic, C++, or any other language, some of the material in Part 2 may be familiar to you. If so, you can skip sections or read this stuff quickly. But don’t read too quickly. Java is a little different from some other programming languages, and Java's differences are worth noting.
Part 3 has some of my favorite chapters. This part covers the all-important topic of object-oriented programming. In these chapters, you find out how to map solutions to big problems. (Sure, the examples in these chapters aren’t big, but the examples involve big ideas.) You discover, in bite-worthy increments, how to design classes, reuse existing classes, and construct objects.
Have you read any of those books that explain object-oriented programming in vague, general terms? I’m very proud to say that Java Programming for Android Developers For Dummies, 2nd Edition, isn’t like that. In this book, I illustrate each concept with a simple-yet-concrete program example.
If you’ve tasted some Java and want more, you can find what you need in Part 4 of this book. This part’s chapters are devoted to details — the things you don’t see when you first glance at the material. This part includes some fully functional Android apps. So, after you read the earlier parts and write some programs on your own, you can dive in a little deeper by reading Part 4.
In The Part of Tens, which is a little Java candy store, you can find lists — lists of tips for avoiding mistakes, tracking down resources, and finding all kinds of interesting goodies.
You’ve read the Java Programming for Android Developers book, seen the Java Programming for Android Developers movie, worn the Java Programming for Android Developers T-shirt, and eaten the Java Programming for Android Developers candy. What more is there to do?
That’s easy. Just visit this book's website: www.allmycode.com/Java4Android
. There you can find updates, comments, additional information, and answers to commonly asked questions from readers. You can also find a small chat application for sending me quick questions when I'm online. (When I'm not online, you can contact me in other ways. See the end of this chapter for more info.)
If you could watch me write this book, you’d see me sitting at my computer, talking to myself. I say each sentence in my head. Most of the sentences I mutter several times. When I have an extra thought, a side comment, or something else that doesn’t belong in the regular stream, I twist my head a little bit. That way, whoever’s listening to me (usually nobody) knows that I’m off on a momentary tangent.
Of course, in print, you can’t see me twisting my head. I need some other way to set a side thought in a corner by itself. I do it with icons. When you see a Tip icon or a Remember icon, you know that I’m taking a quick detour.
Here’s a list of icons that I use in this book:
Answer: A Remember icon.
In addition to what you’re reading right now, this book comes with a free access-anywhere Cheat Sheet containing code that you can copy and paste into your own Android program. To get this Cheat Sheet, simply go to www.dummies.com
and type “Java Programming for Android Developers For Dummies Cheat Sheet” in the Search box.
If you’ve gotten this far, you’re ready to start reading about Java and Android application development. Think of me (the author) as your guide, your host, your personal assistant. I do everything I can to keep things interesting and, most importantly, to help you understand.
1See www.kantarworldpanel.com/global/News/Android-Share-Growth-is-Highest-in-EU5-in-Over-Two-Years
. The EU5 countries are France, Germany, Italy, Spain, and the United Kingdom.
2See www.globalwebindex.net/hubfs/Reports/GWI_Device_Report_-_Q3_2015_Summary.pdf
.
3See www.statista.com/statistics/276623/number-of-apps-available-inleading-app-stores
.
4See www.java.com/en/about
.
Part 1
IN THIS PART …
Downloading the software
Installing Java and Android
Creating dirt-simple Android apps
Testing Android apps on your computer
Chapter 1
IN THIS CHAPTER
The consumer's view of the Android ecosystem
The ten-cent tour of Java and Android technologies
Until the mid-2000s, the word android represented a mechanical, humanlike creature — a rootin’-tootin’ officer of the law with built-in machine guns or a hyperlogical space traveler who can do everything except speak using contractions. And then in 2005, Google purchased Android, Inc. — a 22-month-old company creating software for mobile phones. That move changed everything.
In 2007, a group of 34 companies formed the Open Handset Alliance. Its task is “to accelerate innovation in mobile and offer consumers a richer, less expensive, and better mobile experience”; its primary project is Android, an open, free operating system based on the Linux operating system kernel.
Though HTC released the first commercially available Android phone near the end of 2008, in the United States the public's awareness of Android and its potential didn't surface until early 2010.
Since then, Android's ecosystem has enjoyed steady growth. Kantar Worldpanel ComTech reports (at www.kantarworldpanel.com/global/smartphone-os-market-share/article
): “The latest smartphone OS data … for the three months ending March 2016 shows Android continuing to grow sales across the EU5, US, and Urban China. There were solid gains in the EU5 (Great Britain, Germany, France, Italy, and Spain), up 7.1% points to 75.6%. In the US, Android share increased 7.3% points to 65.5%, and in China, it rose nearly 6% points to over 77%.”1
A consumer considers the alternatives:
Possibility #1: No mobile phone
Advantages: Inexpensive; no interruptions from callers.
Disadvantages: No instant contact with friends and family; no calls to services in case of emergencies.
Possibility #2: A feature phone
This type of mobile phone isn’t a smartphone. Though no official rule defines the boundary between feature phone and smartphone, a feature phone generally has an inflexible menu of Home screen options, compared with a smartphone's ″desktop″ of downloaded apps.
Advantage: Less expensive than a smartphone.
Disadvantages: Less versatile than a smartphone, not nearly as cool as a smartphone, and nowhere near as much fun as a smartphone.
Possibility #3: An iPhone
Advantages: Great-looking graphics.
Disadvantages: Little or no flexibility with the single-vendor iOS operating system; only a handful of models to choose from.
Possibility #4: A Windows phone or another non-Android, non-Apple smartphone
Advantage: Having a smartphone without having to belong to a crowd.
Disadvantage: The possibility of owning an orphan product when the smartphone wars come to a climax.
Possibility #5: An Android phone
Advantages: Using a popular, open platform with lots of industry support and powerful market momentum; writing your own software and installing it on your own phone (without having to post the software on a company's website); publishing software without having to face a challenging approval process.
Disadvantages: Security concerns when using an open platform; dismay when iPhone users make fun of your phone.
For me, Android's advantages far outweigh its possible disadvantages. And you're reading a paragraph from Java Programming for Android Developers For Dummies, 2nd Edition, so you're likely to agree with me.
Version numbers can be tricky. My PC's model number is T420s. When I download the users’ guide, I download one guide for any laptop in the T400 series. (No guide specifically addresses the T420, let alone the T420s.) But when I have driver problems, knowing that I have a T420s isn't good enough. I need drivers that are specific to my laptop's 7-digit model number. The moral to this story: What constitutes a “version number” depends on who's asking for the number.
With that in mind, you can see a history of Android versions in Figure 1-1.
A few notes on Figure 1-1 are in order:
The platform number is of interest to the consumer and to the company that sells the hardware.
If you’re buying a phone with Android 5.1, for example, you might want to know whether the vendor will upgrade your phone to Android 6.0.
The API level (also known as the SDK version) is of interest to the Android app developer.
For example, the word MATCH_PARENT has a specific meaning in Android API Levels 8 and higher. You might type MATCH_PARENT in code that uses API Level 7. If you do (and if you expect MATCH_PARENT to have that specific meaning), you'll get a nasty-looking error message.
You can read more about the Application Programming Interface (API) in Chapter 2. For more information about the use of Android's API levels (SDK versions) in your code, see Chapter 3. For even more information about Android API levels, visit
http://developer.android.com/guide/appendix/api-levels.html-level
The code name is of interest to the creators of Android.
A code name refers to the work done by the creators of Android to bring Android to the next official level. Android's code names are desserts, working in alphabetical order starting with Cupcake, Donut, Eclair, and so on. Picture Google's engineers working for months behind closed doors on Project Marshmallow.
In recent years, this naming scheme has become a lot more transparent. For example, Google created an online poll to help decide on an N word as the successor to Android Marshmallow. After a month of voting, Android Nougat was announced.
As a developer, your job is to balance portability with feature-richness. When you create an app, you specify a minimum Android version. (You can read more about this topic in Chapter 3.) The higher the version, the more features your app can have. On the flip side, the higher the version, the fewer devices that can run your app.
Android is a multifaceted beast. When you develop for the Android platform, you use many toolsets. This section gives you a brief rundown.
James Gosling of Sun Microsystems created the Java programming language in the mid-1990s. (Sun Microsystems has since been bought by Oracle.) Java's meteoric rise in use stemmed from the elegance of the language and its well-conceived platform architecture. After a brief blaze of glory with applets and the web, Java settled into being a solid, general-purpose language with a special strength in servers and middleware.
In the meantime, Java was quietly seeping into embedded processors. Sun Microsystems was developing Java Mobile Edition (Java ME) for creating small apps to run on mobile phones. Java became a major technology in Blu-ray disc players. So the decision to make Java the primary development language for Android apps is no big surprise.
Figure 1-2 describes the development of new Java versions over time. Like Android, each Java version has several names. The product version is an official name that's used for the world in general, and the developer version is a number that identifies versions so that programmers can keep track of them. (In casual conversation, developers use all kinds of names for the various Java versions.) The code name is a more playful name that identifies a version while it's being created.
The asterisks in Figure 1-2 mark changes in the formulation of Java product-version names. Back in 1996, the product versions were Java Development Kit 1.0 and Java Development Kit 1.1. In 1998, someone decided to christen the product Java 2 Standard Edition 1.2, which confuses everyone to this day. At the time, anyone using the term Java Development Kit was asked to use Software Development Kit (SDK) instead.
In 2004 the 1. business went away from the platform version name, and in 2006, Java platform names lost the 2 and the .0. For Java SE 9, the developer versions stopped being numbers like 1.9 and became plain old 9.
By far the most significant changes for Java developers came about with J2SE 5.0 and Java SE 8. With the release of J2SE 5.0, the overseers of Java made changes to the language by adding many new features — features such as generic types, annotations, varargs, and the enhanced for statement. With Java SE 8 came new functional programming features.
If you find View Source among your web browser's options one day and decide to use it, you'll see a bunch of HyperText Markup Language (HTML) tags. A tag is some text, enclosed in angle brackets, that describes something about its neighboring content.
For example, to create boldface type on a web page, a web designer writes
<b>Look at this!</b>
The b tags in angle brackets turn boldface type on and off.
The M in HTML stands for Markup — a general term describing any extra text that annotates a document's content. When you annotate a document's content, you embed information about the content into the document itself. For example, in the previous line of code, the content is Look at this! The markup (information about the content) consists of the tags <b> and </b>.
The HTML standard is an outgrowth of Standard Generalized Markup Language (SGML), an all-things-to-all-people technology for marking up documents for use by all kinds of processors running all kinds of software and sold by all kinds of vendors.
In the mid-1990s, a working group of the World Wide Web Consortium (W3C) began developing the eXtensible Markup Language, commonly known as XML. The working group's goal was to create a subset of SGML for use in transmitting data over the Internet. It succeeded. XML is now a well-established standard for encoding information of all kinds.
Java is good for describing step-by-step instructions, and XML is good for describing the way things are (or the way they should be). A Java program says, “Do this and then do that.” In contrast, an XML document says, “It's this way and it's that way.” Android uses XML for two purposes:
To describe an app's data
An app's XML documents describe the layout of the app's screens, the translations of the app into one or more languages, and other kinds of data.
To describe the app itself
Every Android app has an AndroidManifest.xml file, an XML document that describes features of the app. A device's operating system uses the AndroidManifest.xml document's contents to manage the running of the app.
For example, an app's AndroidManifest.xml file lists the screens that the user sees during a run of the app and tells a device which screen to display when the app is first launched. The same file tells the device which of the app's screens can be borrowed for use by other apps.
Concerning XML, I have bad news and good news. The bad news is that XML isn't always easy to compose. At best, writing XML code is boring. At worst, writing XML code is downright confusing. The good news is that automated software tools compose most of the world's XML code. As an Android programmer, I know that the software on your development processor composes much of your app's XML code. You often tweak the XML code, read part of the code for information from its source, make minor changes, and compose brief additions. But you hardly ever create XML documents from scratch.
An operating system is a big program that manages the overall running of a processor or a device. Most operating systems are built in layers. An operating system's outer layers are usually in the user's face. For example, both Windows and Macintosh OS X have standard desktops. From the desktop, the user launches programs, manages windows, and does other important things.
An operating system's inner layers are (for the most part) invisible to the user. While the user plays Solitaire, for example, the operating system juggles processes, manages files, keeps an eye on security, and generally does the kinds of things that the user shouldn't have to micromanage.
At the deepest level of an operating system is the system's kernel. The kernel runs directly on the processor's hardware and does the low-level work required to make the processor run. In a truly layered system, higher layers accomplish work by making calls to lower layers. So an app with a specific hardware request sends the request (directly or indirectly) through the kernel.
The best-known, best-loved general purpose operating systems are Windows, Macintosh OS X (which is really Unix), and Linux. Both Windows and Mac OS X are the properties of their respective companies. But Linux is open source. That's one reason why your TiVo runs Linux and why the creators of Android based their platform on the Linux kernel.
As a developer, your most intimate contact with the Android operating system is via the command line, also known as the Linux shell. The shell uses commands such as cd to change to a directory, ls to list a directory's files and subdirectories, rm to delete files, and many others.
Google Play has plenty of free terminal apps. A terminal app's interface is a plain-text screen on which you type Linux shell commands. And by using one of Android's developer tools, the Android Debug Bridge, you can issue shell commands to an Android device via your development computer. If you like getting your virtual hands dirty, the Linux shell is for you.
Before Java became popular, running a computer program involved one translation step. Someone (or something) translated the code that a developer wrote into more cryptic code that a computer could actually execute. But then Java came along and added an extra translation layer, and then Android added another layer. This section describes all those layers.
A Java program (such as an Android application program) undergoes several translation steps between the time you write the program and the time a processor runs the program. One of the reasons is simple: Instructions that are convenient for processors to run are not convenient for people to write.
People can write and comprehend the code in Listing 1-1.
LISTING 1-1: Java Source Code
public void checkVacancy(View view) {
if (room.numGuests == 0) {
label.setText("Available");
} else {
label.setText("Taken :-(");
}
}
The Java code in Listing 1-1 checks for a vacancy in a hotel. You can't run the code in this listing without adding several additional lines. But here in Chapter 1, those additional lines aren't important. What's important is that, by staring at the code, squinting a bit, and looking past all its strange punctuation, you can see what the code is trying to do:
If the room has no guests in it,
then set the label's text to "Available".
Otherwise,
set the label's text to "Taken :-(".
The content of Listing 1-1 is Java source code.
The processors in computers, phones, and other devices don't normally follow instructions like the instructions in Listing 1-1. That is, processors don't follow Java source code instructions. Instead, processors follow cryptic instructions like the ones in Listing 1-2.
LISTING 1-2: Java Bytecode
0 aload_0
1 getfield #19 <com/allmycode/samples/MyActivity/room
Lcom/allmycode/samples/Room;>
4 getfield #47 <com/allmycode/samples/Room/numGuests I>
7 ifne 22 (+15)
10 aload_0
11 getfield #41 <com/allmycode/samples/MyActivity/label
Landroid/widget/TextView;>
14 ldc #54 <Available>
16 invokevirtual #56
<android/widget/TextView/setText
(Ljava/lang/CharSequence;)V>
19 goto 31 (+12)
22 aload_0
23 getfield #41 <com/allmycode/samples/MyActivity/label
Landroid/widget/TextView;>
26 ldc #60 <Taken :-(>
28 invokevirtual #56
<android/widget/TextView/setText
(Ljava/lang/CharSequence;)V>
31 return
The instructions in Listing 1-2 aren't Java source code instructions. They're Java bytecode instructions. When you write a Java program, you write source code instructions. (Refer to Listing 1-1.) After writing the source code, you run a program (that is, you apply a tool) to the source code. The program is a compiler: It translates your source code instructions into Java bytecode instructions. In other words, the compiler translates code that you can write and understand (again, refer to Listing 1-1) into code that a processor can execute. (Refer to Listing 1-2.)
At this point, you might ask, “What will I have to do to get the compiler running?” The answer to your question is “Android Studio.” All the translation steps described in this chapter come down to using Android Studio — a piece of software that you download for free using the instructions in Chapter 2. So when you read in this chapter about compiling and other translation steps, don't become intimidated. You don't have to repair an alternator in order to drive a car, and you won't have to understand how compilers work in order to use Android Studio.
If compiling is a good thing, compiling twice is even better.
In 2007, Dan Bornstein at Google created Dalvik bytecode — another way to represent instructions for processors to follow. (To find out where some of Bornstein's ancestors come from, run your favorite map application and look for Dalvik in Iceland.) Dalvik bytecode is optimized for the limited resources on a phone or a tablet device.
Listing 1-3 contains sample Dalvik instructions.
* To see the code in Listing 1-3, I used the Dedexer program (from http://dedexer.sourceforge.net
).
LISTING 1-3: Dalvik Bytecode
.method public checkVacancy(Landroid/view/View;)V
.limit registers 4
; this: v2 (Lcom/allmycode/samples/MyActivity;)
; parameter[0] : v3 (Landroid/view/View;)
.line 30
iget-object
v0,v2,com/allmycode/samples/MyActivity.room
Lcom/allmycode/samples/Room;
; v0 : Lcom/allmycode/samples/Room; , v2 :
Lcom/allmycode/samples/MyActivity;
iget v0,v0,com/allmycode/samples/Room.numGuests I
; v0 : single-length , v0 : single-length
if-nez v0,l4b4
; v0 : single-length
.line 31
iget-object
v0,v2,com/allmycode/samples/MyActivity.label
Landroid/widget/TextView;
; v0 : Landroid/widget/TextView; , v2 :
Lcom/allmycode/samples/MyActivity;
const-string v1,"Available"
; v1 : Ljava/lang/String;
invoke-virtual
{v0,v1},android/widget/TextView/setText
; setText(Ljava/lang/CharSequence;)V
; v0 : Landroid/widget/TextView; , v1 : Ljava/lang/String;
l4b2:
.line 36
return-void
l4b4:
.line 33
iget-object
v0,v2,com/allmycode/samples/MyActivity.label
Landroid/widget/TextView;
; v0 : Landroid/widget/TextView; , v2 :
Lcom/allmycode/samples/MyActivity;
const-string v1,"Taken :-("
; v1 : Ljava/lang/String;
invoke-virtual
{v0,v1},android/widget/TextView/setText ;
setText(Ljava/lang/CharSequence;)V
; v0 : Landroid/widget/TextView; , v1 : Ljava/lang/String;
goto l4b2
.end method
When you create an app, Android Studio performs at least two compilations:
But that's not all! In addition to its Java code, an Android app has XML files, image files, and possibly other elements. Before you install an app on a device, Android Studio combines all these elements into a single file — one with the .apk extension. When you publish the app on an app store, you copy that .apk file to the app store's servers. Then, to install your app, a user visits the app store and downloads your .apk file.
In the section “What is a compiler?” earlier in this chapter, I make a big fuss about phones and other devices following instructions like the ones in Listing 1-3. As fusses go, it's a nice fuss. But if you don't read every fussy word, you may be misguided. The exact wording is “… processors follow cryptic instructions like the ones in Listing ‘blah-blah-blah.’” The instructions in Listing 1-3 are a lot like instructions that a phone or tablet can execute, but computers generally don't execute Java bytecode instructions, and phones don't execute Dalvik bytecode instructions. Instead, each kind of processor has its own set of executable instructions, and each operating system uses the processor's instructions in a slightly different way.
Imagine that you have two different devices: a smartphone and a tablet computer. The devices have two different kinds of processors: The phone has an ARM processor, and the tablet has an Intel Atom processor. (The acronym ARM once stood for Advanced RISC Machine. These days, ARM simply stands for ARM Holdings, a company whose employees design processors.) On the ARM processor, the multiply instruction is 000000. On an Intel processor, the multiply instructions are D8, DC, F6, F7, and others. Many ARM instructions have no counterparts in the Atom architecture, and many Atom instructions have no equivalents on an ARM processor. An ARM processor's instructions make no sense to your tablet's Atom processor, and an Atom processor's instructions would give your phone's ARM processor a virtual headache.
What's a developer to do? Does a developer provide translations of every app into every processor's instruction set?
No. Virtual machines create order from all this chaos. Dalvik bytecode is similar to the code in Listing 1-3, but Dalvik bytecode isn't specific to a single kind of processor or to a single operating system. Instead, a set of Dalvik bytecode instructions runs on any processor. If you write a Java program and compile that Java program into Dalvik bytecode, your Android phone can run the bytecode, your Android tablet can run the bytecode, your Chromebook can run the bytecode, and even your grandmother's supercomputer can run the bytecode. (If your grandmother wants to do this, she should install Remix OS, a special port of the Android operating system, on her Intel-based machine. Tell her to visit www.jide.com/remixos-for-pc
.)
Both Java bytecode and Dalvik bytecode have virtual machines. Java bytecode's virtual machine is called (big surprise) the Java virtual machine (JVM). Dalvik bytecode's virtual machine is called the Android runtime (ART).
With the Android runtime, you can take a bytecode file that you created for one Android device, copy the bytecode to another Android device, and then run the bytecode with no trouble. That’s one of the many reasons Android has become popular quickly. This outstanding feature, which lets you run code on many different kinds of processors, is called portability.
Imagine that you're the Intel representative to the United Nations Security Council, as shown in Figure 1-3. The ARM representative is seated to your right, and the representative from Qualcomm is to your left. (Naturally, you don't get along with either of these people. You're always cordial to one another, but you're never sincere. What do you expect? It's politics!) The distinguished representative from Dalvik is at the podium. The Dalvik representative speaks in Dalvik bytecode, and neither you nor your fellow ambassadors (ARM and Qualcomm) understand a word of Dalvik bytecode.
But each of you has an interpreter. Your interpreter translates from Dalvik bytecode to Intel instructions as the Dalvik representative speaks. Another interpreter translates from bytecode to “ARM-ese.” And a third interpreter translates bytecode into “Qualcomm-speak.”
Think of your interpreter as a virtual ambassador. The interpreter doesn't really represent your country, but the interpreter performs one important task that a real ambassador performs: It listens to Dalvik bytecode on your behalf. The interpreter does what you would do if your native language were Dalvik bytecode. The interpreter, pretending to be the Intel ambassador, endures the boring bytecode speech, taking in every word and processing each one in some way or another.
You have an interpreter — a virtual ambassador. In the same way, an Intel processor runs its own bytecode-interpreting software. That software is the Dalvik virtual machine — a proxy, an errand boy, a go-between. The Android runtime serves as an interpreter between Dalvik's run-anywhere bytecode and your device's own system. As it runs, the virtual machine walks your device through the execution of bytecode instructions. It examines your bytecode, bit by bit, and carries out the instructions described in the bytecode. The virtual machine interprets bytecode for your ARM processor, your Intel processor, your Qualcomm chip, or whatever kind of processor you’re using. That’s a good thing. It’s what makes Java code and Dalvik code more portable than code written in any other language.
“You don't see the forest for the trees,” said my Uncle Harvey. To which my Aunt Clara said, “You don't see the trees for the forest.” This argument went on until they were both too tired to discuss the matter.
As an author, I like to present both the forest and the trees. The “forest” is the broad overview, which helps you understand why you perform various steps. The “trees” are the steps themselves, getting you from Point A to Point B until you complete a task.
This chapter shows you the forest. The rest of this book shows you the trees.
1 See www.kantarworldpanel.com/global/smartphone-os-market-share/article
.
Chapter 2