22,99 €
Develop the next killer Android App using Java programming! Android is everywhere! It runs more than half the smartphones in the U.S.--and Java makes it go. If you want to cash in on its popularity by learning to build Android apps with Java, all the easy-to-follow guidance you need to get started is at your fingertips. Inside, you'll learn the basics of Java and grasp how it works with Android; then, you'll go on to create your first real, working application. How cool is that? The demand for Android apps isn't showing any signs of slowing, but if you're a mobile developer who wants to get in on the action, it's vital that you get the necessary Java background to be a success. With the help of Java Programming for Android Developers For Dummies, you'll quickly and painlessly discover the ins and outs of using Java to create groundbreaking Android apps--no prior knowledge or experience required! * Get the know-how to create an Android program from the ground up * Make sense of basic Java development concepts and techniques * Develop the skills to handle programming challenges * Find out how to debug your app Don't sit back and watch other developers release apps that bring in the bucks! Everything you need to create that next killer Android app is just a page away!
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 491
Veröffentlichungsjahr: 2016
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)
Table of Contents
Cover
Introduction
How to Use This Book
Conventions Used in This Book
What You Don’t Have to Read
Foolish Assumptions
How This Book Is Organized
Icons Used in This Book
Beyond the Book
Where to Go from Here
Part 1: Getting Started with Java Programming for Android Developers
Chapter 1: All about Java and Android
The Consumer Perspective
The Many Faces of Android
The Developer Perspective
From Development to Execution with Java
Java, Android, and Horticulture
Chapter 2: Getting the Tools That You Need
The Stuff You Need
If You Don't Like to Read the Instructions …
Getting This Book's Sample Programs
Setting Up Java
Setting Up Android Studio and the Android SDK
Launching the Android Studio IDE
Opening One of This Book's Sample Programs
Using Android Studio
Things You Might Eventually Have to Do
Chapter 3: Creating and Running an Android App
Creating Your First App
If the Emulator Doesn't Behave
The Project Tool Window
Dragging, Dropping, and Otherwise Tweaking an App
What All That Java Code Does
Going Pro
Part 2: Writing Your Own Java Programs
Chapter 4: An Ode to Code
Hello, Android!
The Java Class
Why Java Methods Are Like Meals at a Restaurant
Punctuating Your Code
All About Android Activities
Chapter 5: Java's Building Blocks
Info Is As Info Does
Things You Can Do with Types
Chapter 6: Working with Java Types
Working with Strings
Practice Safe Typing
Chapter 7: Though These Be Methods, Yet There Is Madness in't
Minding Your Types When You Call a Method
Primitive Types and Pass-by Value
Chapter 8: What Java Does (and When)
Making Decisions
Repeating Instructions Over and Over Again
What's Next?
Part 3: Working with the Big Picture: Object-Oriented Programming
Chapter 9: Why Object-Oriented Programming Is Like Selling Cheese
Classes and Objects
More About Classes and Objects (Adding Methods to the Mix)
Java's Modifiers
What's Next?
Chapter 10: Saving Time and Money: Reusing Existing Code
The Last Word on Employees — Or Is It?
More about Java's Modifiers
Keeping Things Simple
Some Observations about Android's Classes
Part 4: Powering Android with Java Code
Chapter 11: The Inside Story
A Button-Click Example
Introducing Inner Classes
No Publicity, Please!
Lambda Expressions
Chapter 12: Dealing with a Bunch of Things at a Time
Creating a Collection Class
Stepping Through a Collection
Java's Many Collection Classes
Arrays
Using Collections in an Android App
Chapter 13: An Android Social Media App
The Twitter App's Files
How to Talk to the Twitter Server
The Application's Main Activity
Java's Exceptions
Chapter 14: Hungry Burds: A Simple Android Game
Introducing the Hungry Burds Game
The Main Activity
It's Been Fun
Part 5: The Part of Tens
Chapter 15: Ten Ways to Avoid Mistakes
Putting Capital Letters Where They Belong
Breaking Out of a switch Statement
Comparing Values with a Double Equal Sign
Adding Listeners to Handle Events
Defining the Required Constructors
Fixing Nonstatic References
Staying within Bounds in an Array
Anticipating Null Pointers
Using Permissions
The Activity Not Found
Chapter 16: Ten Websites for Developers
This Book's Websites
The Horse's Mouth
Finding News and Reviews
About the Author
Advertisement Page
Connect with Dummies
End User License Agreement
Cover
Table of Contents
Begin Reading
i
ii
v
vi
vii
viii
ix
x
xi
1
2
3
4
5
6
7
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
439
440
441
442
443
444
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:
If you already know something, don’t bother reading about it.
If you’re curious, don’t be afraid to skip ahead. You can always sneak a peek at an earlier chapter, if you need to do so.
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:
New terms are set in
italics.
If you need to type something that’s mixed in with the regular text, the characters you type appear in bold. For example: “Type
MyNewProject
in the text field.”
You also see this
computerese
font. I use computerese for Java code, filenames, onscreen messages, and other such things. Also, if something you need to type is really long, it appears in computerese font on its own line (or lines).
You may need to change certain things when you type them on your own computer keyboard. For instance, I may ask you to type
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 already know what kind of an animal Java is and you don't care what happens behind the scenes when an Android app runs:
Skip
Chapter 1
and go straight to
Chapter 2
. Believe me — I won’t mind.
If you already know how to get an Android app running:
Skip
Part 1
and start with
Part 2
.
If you have experience writing computer programs in languages other than C and C++:
Start with
Part 2
. You’ll probably find
Part II
to be easy reading. When you get to
Part 3
, it’ll be time to dive in.
If you have experience writing computer programs in C or C++:
Skim
Part II
and start reading seriously in
Part 3
. (Java is a bit different from C++ in the way it handles classes and objects.)
If you have experience writing Java programs:
Come to my house and help me write
Java Programming for Android Developers For Dummies,
3rd Edition.
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 have access to a computer.
Access to an Android device is helpful but not absolutely necessary! All the software you need in order to test Android apps on a laptop or desktop computer is freely available. You simply download, install, and get going.
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 assume that you can think logically.
That’s all there is to application development — thinking logically. If you can think logically, you’ve got it made. If you don’t believe that you can think logically, read on. You may be pleasantly surprised.
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:
A tip is an extra piece of information — helpful advice that the other books may forget to tell you.
Everyone makes mistakes. Heaven knows that I’ve made a few in my time. Anyway, when I think people are especially prone to make a mistake, I mark the text with a Warning icon.
Question: What’s stronger than a tip but not as strong as a warning?
Answer: A Remember icon.
“If you don’t remember what such-and-such means, see blah-blah-blah,” or “For more information, read blahbity-blah-blah.”
This icon calls attention to useful material that you can find online. (You don’t have to wait long to see one of these icons. I use one at the end of this introduction!)
Occasionally, I run across a technical tidbit. The tidbit may help you understand what the people behind the scenes (the people who created Java) were thinking. You don’t have to read it, but you may find it useful. You may also find the tidbit helpful if you plan to read other (geekier) books about Java and Android.
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.
If you like what you read, send me a note. My email address, which I created just for comments and questions about this book, is java4android @allmycode.com. If email and chat aren't your favorites, you can reach me instead on Twitter (@allmycode) and on Facebook (/allmycode). And don’t forget — for the latest updates, visit this book’s website. The site's address is www.allmycode.com/java4android.
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.
FIGURE 1-1: Versions of Android.
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.
An Android version may have variations. For example, plain ol’ Android 6.0 has an established set of features. To plain ol’ Android 6.0 you can add the Google Play Services (the ability to install apps from Google Play) and still be using platform 6.0. You can also add a special set of features tailored for various phone manufacturers.
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.
An embedded processor is a computer chip that is hidden from the user as part of a special-purpose device. The chips in cars are now embedded processors, and the silicon that powers the photocopier at your workplace is an embedded processor. Pretty soon, the flowerpots on your windowsill will probably have embedded processors.
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.
FIGURE 1-2: Versions of Java.
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.
To see Java annotations in action, go to Chapter 10. For examples of the use of generic types, varargs, and the enhanced for statement, see Chapter 12. To read about functional programming features, see Chapter 11.
In addition to all the numbers in Figure 1-2, you'll see codes like Java SE 8u91. A code such as 8u91 stands for the 91st update of Java 8. For a novice Java developer, these updates don't make very much difference.
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.
For an overview of XML, see the sidebar “All about XML files” in Chapter 3.
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.
For more information about the AndroidManifest.xml file, see Chapter 4.
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.
“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
IN THIS CHAPTER
Installing Java
Downloading and installing the Android software tools
Checking your Android Studio installation
Getting the code in this book's examples
ergaliophilenoun 1. A lover of tools. 2. A person who visits garage sales for rusty metal implements that might be useful someday but probably won't. 3. A person whose computer runs slowly because of the daily, indiscriminate installation of free software tools.
Several years ago, I found an enormous monkey wrench (more than a yard long and weighing 35 pounds) at a nearby garage sale. I wasn't a good plumber, and to this day any pipe that I fix starts leaking again immediately. But I couldn't resist buying this fine piece of hardware. The only problem was, my wife was sitting in the car about halfway down the street. She's much more sensible than I am about these matters, so I couldn't bring the wrench back to the car. “Put it aside and I'll come back for it later,” I told the seller.
When I returned to the car empty-handed, my wife said, “I saw someone carrying the world's largest pipe wrench. I'm glad you weren't the one who bought it.” And I agreed with her. “I don't need more junk like that.”
So of course I returned later that day to buy the monkey wrench, and to this day the wrench sits in our attic, where no one ever sees it. If my wife ever reads this chapter, she'll be either amused or angry. I hope she's not angry, but I'm taking the risk because I enjoy the little drama. To add excitement to my life, I'm turning this trivial secret into a public announcement.
This book tells you how to write Java programs, and before you can write them, you need some software tools. Here's a list of the tools you need:
The Java Development Kit (JDK)
This includes a Java virtual machine, the Java code libraries, and some additional software for developing Java code.
An integrated development environment
You can create Android apps using geeky, keyboard-only tools, but eventually you'll tire of typing and retyping commands. An integrated development environment (IDE), on the other hand, is a little like a word processor: A word processor helps you compose documents (memos, poems, and other works of fine literature); in contrast, an IDE helps you compose instructions for processors.
For composing Android apps, you need the Android Studio IDE.
The Android Software Development Kit
The Android Software Development Kit (SDK) includes lots and lots of prewritten, reusable Android code and a bunch of software tools for running and testing Android apps.
The prewritten Android code is the Android Application Programming Interface (API). The API comes in several versions — versions 21 and 22 (both code-named Lollipop), version 23 (Marshmallow), version 24 (Nougat), and so on.
Some sample Android code projects to help you get started
All examples in this book are available for download from www.allmycode.com/Java4Android.
All these tools run on the development computer — the laptop or desktop computer you use to develop Java programs and Android apps. After you create an Android app, you copy the app's code from the development computer to a target device — a phone, a tablet, or (someday soon) a refrigerator that runs Android.
Here's good news: You can download from the web all the software you need to run this book's examples for free. The software is separated into three downloads:
When you visit
www.oracle.com/technetwork/java/javase/downloads
, you can click a button to install the Java JDK.
A button at the page
http://developer.android.com/studio
gives you the Android Studio IDE download and the Android Software Development Kit.
This book's website (
www.allmycode.com/Java4Android
) has a link to all code in this book.
The Java and Android websites I describe in this chapter are always changing. The software programs you download from these sites change, too. A specific instruction such as “Click the button in the upper-right corner” becomes obsolete (and even misleading) in no time at all. So, in this chapter, I provide explicit steps, but I also describe the ideas behind them. Browse the suggested sites and look for ways to get the software I describe. When a website offers you several options, check the instructions in this chapter for hints on choosing the best option. If your Android Studio window doesn't look quite like the one in this chapter's figures, scan your computer's window for whatever options I describe. If, after all that effort, you can't find the elements you're looking for, check this book's website (www.allmycode.com/Java4Android) or send an email to me at [email protected].
I start this chapter with a brief (but useful) overview of the steps required in order to set up the software you need. If you're an old hand at installing software, and if your computer isn't quirky, these fast-track steps will probably serve you well. If not, you can read the more detailed instructions in the next several sections.
Visitwww.allmycode.com/Java4Androidand download a file containing all the program examples in this book.
The downloaded file is a .zip archive file. (See the sidebars entitled “Those pesky filename extensions” and “Compressed archive files , later in this chapter.”)
Extract the contents of the downloaded file to a place on your computer's hard drive.
Visitwww.oracle.com/technetwork/java/javase/downloadsand download the Java Standard Edition JDK.
Choose a version of the software that matches your operating system (Windows, Macintosh, or whatever) and your operating system's word length (32-bit or 64-bit).
Install the Java Standard Edition JDK.
Double-click the .exe file or the .dmg file that you downloaded in Step 3, and proceed with whatever steps you usually take when you install software.
Visithttp://developer.android.com/studioand download the Android Studio IDE along with the Android Software Development Kit (SDK).
The combined download bundle is an .exe file, a .dmg file, or a .zip file (or maybe something else).
Install the software that you downloaded in Step 5.
Double-click the downloaded file, accept all kinds of legal disclaimers, drag things, drop things, and so on.
Launch the Android Studio application.
The first time you run a fresh, new copy of Android Studio, you see some introductory screens.
Click past the introductory screens until you see a screen with options like Start a New Android Studio Project and Open an Existing Android Studio Project.