Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks ofO’Reilly Media, Inc. Building Android Apps with HTML, CSS, and JavaScript, the image of a maleo, andrelated trade dress are trademarks of O’Reilly Media, Inc.Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of atrademark claim, the designations have been printed in caps or initial caps.While every precaution has been taken in the preparation of this book, the publisher and author assumeno responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

TM

This book uses RepKover™, a durable and flexible lay-flat binding.ISBN: 978-1-449-38326-8[M]1284478806

Create an Android Virtual DeviceBuild KiloGapInstalling KiloGap in the EmulatorUsing the Screen’s Full HeightCustomizing the App IconInstalling KiloGap on Your PhoneControlling the Phone with JavaScriptBeep, Vibrate, and AlertGeolocationAccelerometerWhat You’ve Learned

Thanks to mobile phones, we have moved from virtually no one having access to information to virtually everyone having access to the vast resources of the Web. This isarguably the most important achievement of our generation. Despite its overarchingimportance, mobile computing is in its infancy. Technical, financial, and political forceshave created platform fragmentation like never before, and it’s going to get worse beforeit gets better.Developers who need to engage large and diverse groups of people are faced with aseemingly impossible challenge: “How do we implement our mobile vision in a waythat is feasible, affordable, and reaches the greatest number of participants?” In manycases, the answer is web technologies. The combination of advances in HTML5 andmobile devices has created an environment in which even novice developers can buildmobile apps that improve people’s lives on a global scale.Google’s Android operating system is a compelling addition to the mobile computingspace. In true Google fashion, the platform is open, free, and highly interoperable. Thedevelopment tools are full-featured and powerful, if a bit geeky, and run on a varietyof platforms.Carriers and handset manufacturers have jumped on the Android bandwagon. Themarket is beginning to flood with Android devices of all shapes and sizes. This is adouble-edged sword for developers. On one hand, more devices means a bigger market.On the other hand, more devices means more fragmentation. As with the fragmentationin the general mobile market, fragmentation on Android can often be addressed bybuilding apps with HTML, CSS, and JavaScript.I’m the first to admit that not all apps are a good fit for development with web technologies. That said, I see a lot of apps written with native code that could have just aseasily been done with HTML. When speaking to developers who aren’t sure whichapproach to take, I say this:If you can build your app with HTML, CSS, and JavaScript, you probably should.

xi

www.it-ebooks.info

Using open source, standards-based web technologies gives you the greatest flexibility,the broadest reach, and the lowest cost. You can easily release it as a web app, thendebug and test it under load with thousands of real users. Once you are ready to rock,you can use PhoneGap to convert your web app to a native Android app, add a fewdevice-specific features if you like, and submit to the Android Market—or offer it fordownload from your website. Sounds good, right?

Who Should Read This BookI’m going to assume you have some basic experience reading and writing HTML, CSS,and JavaScript (jQuery in particular). Chapter 5 includes some basic SQL code, so apassing familiarity with SQL syntax would be helpful but is not required.

What You Need to Use This BookThis book avoids the Android SDK wherever possible. All you need to follow alongwith the vast majority of examples is a text editor and the most recent version of GoogleChrome (a cutting-edge web browser that’s available for both Mac and Windows athttp://www.google.com/chrome). You do need to have the Android SDK for the PhoneGap material in Chapter 7, where I explain how to convert your web app into a nativeapp that you can submit to the Android Market.

Conventions Used in This BookThe following typographical conventions are used in this book:ItalicIndicates new terms, URLs, email addresses, filenames, and file extensions.Constant width

Used for program listings, as well as within paragraphs to refer to program elementssuch as variable or function names, databases, data types, environment variables,statements, and keywords.Constant width bold

Shows commands or other text that should be typed literally by the user.Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.This icon signifies a tip, suggestion, or general note.

xii | Preface

www.it-ebooks.info

This icon indicates a warning or caution.

Using Code ExamplesThis book is here to help you get your job done. In general, you may use the code inthis book in your programs and documentation. You do not need to contact us forpermission unless you’re reproducing a significant portion of the code. For example,writing a program that uses several chunks of code from this book does not requirepermission. Selling or distributing a CD-ROM of examples from O’Reilly books doesrequire permission. Answering a question by citing this book and quoting examplecode does not require permission. Incorporating a significant amount of example codefrom this book into your product’s documentation does require permission.We appreciate, but do not require, attribution. An attribution usually includes the title,author, publisher, and ISBN. For example: “Building Android Apps with HTML,CSS, and JavaScript by Jonathan Stark. Copyright 2010 Jonathan Stark,978-1-449-38326-8.”If you feel your use of code examples falls outside fair use or the permission given above,feel free to contact us at permissions@oreilly.com.

Safari® Books OnlineSafari Books Online is an on-demand digital library that lets you easilysearch over 7,500 technology and creative reference books and videos tofind the answers you need quickly.With a subscription, you can read any page and watch any video from our library online.Read books on your cell phone and mobile devices. Access new titles before they areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features.O’Reilly Media has uploaded this book to the Safari Books Online service. To have fulldigital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.

Preface | xiii

www.it-ebooks.info

How to Contact UsPlease address comments and questions concerning this book to the publisher:O’Reilly Media, Inc.1005 Gravenstein Highway NorthSebastopol, CA 95472800-998-9938 (in the United States or Canada)707-829-0515 (international or local)707-829-0104 (fax)We have a web page for this book, where we list errata, examples, and any additionalinformation. You can access this page at:http://www.oreilly.com/catalog/9781449383268To comment or ask technical questions about this book, send email to:bookquestions@oreilly.comFor more information about our books, conferences, Resource Centers, and theO’Reilly Network, see our website at:http://www.oreilly.com

AcknowledgmentsWriting a book is a team effort. My heartfelt thanks go out to the following people fortheir generous contributions.Tim O’Reilly, Brian Jepson, and the rest of the gang at ORM for making the experienceof writing this book so rewarding and educational.David Kaneda for his wonderfully obsessive pursuit of beauty. Whether it’s a bit ofcode or a user interface animation, he can’t sleep until it’s perfect, and I love that.The gang at Nitobi for creating and continuing to support PhoneGap.Brian Fling for broadening my view of mobile beyond just the latest and greatest hardware. Brian knows mobile from back in the day; he’s a wonderful writer, and on topof that, a very generous guy.PPK, John Gruber, John Allsopp, and John Resig for their contributions to and supportof the underlying technologies that made this book possible.Joe Bowser, Brian LeRoux, Sara Czyzewicz, and the swarm of folks who generouslyposted comments and questions on the OFPS site for this book. Your feedback wasvery helpful and much appreciated.My wonderful family, friends, and clients for being understanding and supportive whileI was chained to the keyboard.

xiv | Preface

www.it-ebooks.info

And finally, Erica. You make everything possible. I love you!

Preface | xv

www.it-ebooks.info

www.it-ebooks.info

CHAPTER 1

Getting Started

Before we dive in, I’d like to quickly establish the playing field. In this chapter, I’ll definekey terms, compare the pros and cons of the two most common development approaches, and give a crash course on the three core web technologies used in this book.

Web Apps Versus Native AppsFirst, I’d like to define what I mean by web app and native app and consider their prosand cons.

What Is a Web App?To me, a web app is basically a website that is specifically optimized for use on asmartphone. The site content can be anything from a standard small business brochuresite to a mortgage calculator to a daily calorie tracker—the content is irrelevant. Thedefining characteristics of a web app are that the user interface (UI) is built with webstandard technologies, it is available at a URL (public, private, or perhaps behind alogin), and it is optimized for the characteristics of a mobile device. A web app is notinstalled on the phone, it is not available in the Android Market, and it is not writtenwith Java.

What Is a Native App?In contrast, native apps are installed on the Android phone, they have access to thehardware (speakers, accelerometer, camera, etc.), and they are written with Java. Thedefining characteristic of a native app, however, is that it’s available in the AndroidMarket—a feature that has captured the imagination of a horde of software entrepreneurs worldwide, me included.

1

www.it-ebooks.info

Pros and ConsDifferent applications have different requirements. Some apps are a better fit with webtechnologies than others. Knowing the pros and cons of each approach will help youmake a better decision about which path is appropriate for your situation.Here are the pros of native app development:• Millions of registered credit card owners are one click away• You can access all the cool hardware features of the deviceHere are the cons of native app development:••••

You have to pay to become an Android developerYour app will run only on Android phonesYou have to develop using JavaThe development cycle is slow (develop, compile, deploy, repeat)

Here are the pros of web app development:•••••

Web developers can use their current authoring toolsYou can use your current web design and development skillsYour app will run on any device that has a web browserYou can fix bugs in real timeThe development cycle is fast

Here are the cons of web app development:• You cannot access the all cool hardware features of the phone• You have to roll your own payment system if you want to charge for the app• It can be difficult to achieve sophisticated UI effects

Which Approach Is Right for You?Here’s where it gets exciting. The always-online nature of the Android phone createsan environment in which the lines between a web app and a native app get blurry. Thereare even some little-known features of the Android web browser (see Chapter 6) thatallow you to take a web app offline if you want. What’s more, several third-partyprojects—of which PhoneGap is the most notable—are actively developing solutionsthat allow web developers to take a web app and package it as a native app for Androidand other mobile platforms.For me, this is the perfect blend. I can write in my native language, release a productas a pure web app (for Android and any other devices that have a modern browser),and use the same code base to create an enhanced native version that can access thedevice hardware and potentially be sold in the Android Market. This is a great way to2 | Chapter 1: Getting Started

www.it-ebooks.info

create a “fremium” model for your app—allow free access to the web app and chargefor the more feature-rich native version.

Web Programming Crash CourseThe three main technologies we will use to build web apps are HTML, CSS, and JavaScript. We’ll quickly cover each to make sure we’re all on the same page before plowinginto the fancy stuff.

Introduction to HTMLWhen you are browsing the web, the pages you are viewing are just text documentssitting on someone else’s computer. The text in a typical web page is wrapped in HTMLtags, which tell your browser about the structure of the document. With this information, the browser can decide how to display the information in a way that makes sense.Consider the web page snippet shown in Example 1-1. On the first line, the string Hithere! is wrapped in a pair of h1 tags. Notice that the open tag and the close tag areslightly different: the close tag has a slash (/) as the second character, while the opentag does not have a slash.Wrapping text in h1 tags tells the browser that the words enclosed are a heading, whichwill cause it to be displayed in large bold text on its own line. There are also h2, h3, h4,h5, and h6 heading tags. The lower the number, the more important the header, so textwrapped in an h6 tag will be smaller (i.e., less important-looking) than text wrapped inan h3 tag.After the h1 tag in Example 1-1, there are two lines wrapped in p tags. These are calledparagraph tags. Browsers will display each paragraph on its own line. If the paragraphis long enough to exceed the width of the browser window, the text will bump downand continue on the next line. In either case, a blank line will be inserted after theparagraph to separate it from the next item on the page.Example 1-1. HTML snippet

Hi there!

Thanks for visiting my web page.

I hope you like it.

You can also put HTML tags inside other HTML tags. Example 1-2 shows an unorderedlist (ul) tag that contains three list items (li). In a browser, this appears as a bulletedlist with each item on its own line. When you have a tag or tags inside another tag, theinner tags are called child elements, or children, of the parent tag. So in this example,the li tags are children of the ul parent.

Web Programming Crash Course | 3

www.it-ebooks.info

Example 1-2. Unordered list

Pizza

Beer

Dogs

The tags covered so far are all block tags. The defining characteristic of block tags isthat they are displayed on a line of their own, with no elements to the left or right ofthem. That is why the heading, paragraphs, and list items progress down the pageinstead of across it. The opposite of a block tag is an inline tag, which, as the nameimplies, can appear in a line. The emphasis tag (em) is an example of an inline tag, andit looks like this:

I really hope you like it.

The granddaddy of the inline tags—and arguably the coolest feature of HTML—is thea tag. The “a” stands for anchor, but at times I’ll also refer to it as a link or hyperlink.Text wrapped in an anchor tag is clickable, such that clicking on it causes the browserto load a new HTML page.To tell the browser which new page to load, we have to add what’s called an attribute to the tag. Attributes are named values that you insert into an open tag. In an anchortag, you use the href attribute to specify the location of the target page. Here’s a linkto Google’s home page:Google

That might look like a bit of a jumble if you are not used to reading HTML, but youshould be able to pick out the URL for the Google home page. You’ll be seeing a lot ofa tags and href attributes throughout the book, so take a minute to get your head aroundthis if it doesn’t make sense at first glance.There are a couple of things to keep in mind regarding attributes. Different HTML tags allow different attributes. You can add multipleattributes to an open tag by separating them with spaces. You never addattributes to a closing tag. There are hundreds of possible combinationsof attributes and tags, but don’t sweat it—we only have to worry abouta dozen or so in this entire book.

The HTML snippet that we’ve been looking at would normally reside in the body sectionof a complete HTML document. An HTML document is made up of two sections: thehead and the body. The body is where you put all the content that you want users tosee. The head contains information about the page, most of which is invisible to theuser.

4 | Chapter 1: Getting Started

www.it-ebooks.info

The body and head are always wrapped in an html element. Example 1-3 shows thesnippet in the context of a proper HTML document. For now the head section contains a title element, which tells the browser what text to display in the title bar of thewindow.Example 1-3. A proper HTML document

My Awesome Page

Hi there!

Thanks for visiting my web page.

I hope you like it.

Pizza

Beer

Dogs

Normally, when you are using your web browser you are viewing pages that are hostedon the Internet. However, browsers are perfectly good at displaying HTML documentsthat are on your local machine as well. To show you what I mean, I invite you to crackopen a text editor and enter the code in Example 1-3.

Picking the Right Text EditorSome text editors are not suited for authoring HTML. In particular, you want to avoideditors that support rich text editing, like Microsoft WordPad (Windows) or TextEdit(Mac OS X). These types of editors can save their files in formats other than plain text,which will break your HTML. If you must use TextEdit, save in plain text by choosingFormat→Make Plain Text. In Windows, use Notepad instead of WordPad.If you are in the market for a good text editor, my recommendation on the Mac isTextMate. There is a clone version for Windows called E Text Editor.If free is your thing, you can download Text Wrangler for Mac. For Windows, Notepad2 and Notepad++ are highly regarded. Linux comes with an assortment of texteditors, such as vi, nano, emacs, and gedit.

When you are finished entering the code from Example 1-3, save it to your desktop astest.html and then open it with Chrome by either dragging the file onto the Chromeapplication icon or opening Chrome and selecting File→Open File. Double-clickingtest.html will work as well, but it could open in your text editor or another browser,depending on your settings.Web Programming Crash Course | 5

www.it-ebooks.info

Even if you aren’t running Mac OS X, you should use Chrome whentesting your Android web apps on a desktop web browser, becauseChrome is the closest desktop browser to Android’s mobile browser.Chrome is available for Mac and Windows from http://google.com/chrome.

Introduction to CSSAs you’ve seen, browsers render certain HTML elements with distinct styles (for example, headings are large and bold, paragraphs are followed by a blank line, and soforth). These styles are very basic and are primarily intended to help the reader understand the structure and meaning of the document.To go beyond this simple structure-based rendering, you use Cascading Style Sheets(CSS). CSS is a stylesheet language that you use to define the visual presentation of anHTML document. You can use CSS to define simple things like the text color, size, andstyle (bold, italic, etc.), or complex things like page layout, gradients, opacity, and muchmore.Example 1-4 shows a CSS rule that instructs the browser to display any text in the bodyelement using the color red. In this example, body is the selector (this specifies what isaffected by the rule) and the curly braces enclose the declaration (the rule itself). Thedeclaration includes a set of properties and their values. In this example, color is theproperty, and red is the value of the color property.Example 1-4. A simple CSS rulebody { color: red; }

Property names are predefined in the CSS specification, which means that you can’tjust make them up. Each property expects an appropriate value, and there can be lotsof appropriate values and value formats for a given property.For example, you can specify colors with predefined keywords like red, or by usingHTML color code notation, which uses a hexadecimal notation: a hash/pound sign(#) followed by three pairs of hexadecimal digits (0–F) representing (from left to right)red, green, and blue values (red is represented as #FF0000). Properties that expect measurements can accept values like 10px, 75%, and 1em. Example 1-5 shows some commondeclarations. The color code shown for background-color corresponds to the CSS“gray.”Example 1-5. Some common CSS declarationsbody {color: red;background-color: #808080;font-size: 12px;font-style: italic;font-weight: bold;

6 | Chapter 1: Getting Started

www.it-ebooks.info

}

font-family: Arial;

Selectors come in a variety of flavors. If you want all of your hyperlinks (the a element)to display in italics, add the following to your stylesheet:a { font-style: italic; }

If you want to be more specific and only italicize the hyperlinks that are containedsomewhere within an h1 tag, add the following to your stylesheet:h1 a { font-style: italic; }

You can also define your own custom selectors by adding id and/or class attributes toyour HTML tags. Consider the following HTML snippet:

Hi there!

Thanks for visiting my web page.

I hope you like it.

Pizza

Beer

Dogs

If we add .loud { font-style: italic; } to the CSS for this HTML, Hi there! andPizza will show up italicized because they both have the loud class. The dot in front ofthe .loud selector is important—it’s how the CSS knows to look for HTML tags witha class of loud. If you omit the dot, the CSS will look for a loud tag, which doesn’t existin this snippet (or in HTML at all, for that matter).Applying CSS by id is similar. To add a yellow background fill to the highlight paragraph tag, use the following rule:#highlight { background-color: yellow; }

Here, the # symbol tells the CSS to look for an HTML tag with the ID highlight.To recap, you can opt to select elements by tag name (e.g., body, h1, p), by class name(e.g., .loud, .subtle, .error), or by ID (e.g., #highlight, #login, #promo). And, you canget more specific by chaining selectors together (e.g., h1 a, body ul .loud).There are differences between class and id. Use class attributes whenyou have more than one item on the page with the same class value.Conversely, id values have to be unique to a page.When I first learned this, I figured I’d just always use class attributes soI wouldn’t have to worry about whether I was duping an ID value.However, selecting elements by ID is much faster than by class, so youcan hurt your performance by overusing class selectors.