All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2013
Production Reference: 1070213
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84951-940-3 www.packtpub.com
Cover Image by Siddharth Ravishankar ()
www.it-ebooks.info
Credits Author
Project Coordinator
Kerri Shotts
Abhishek Kori
Reviewers
Proofreader
Steve Husting
Sandra Hopper
Johnathan Iannotti Indexers
Tony Pye
Hemangini Bari Tejal Soni
Acquisition Editor Aarthi Kumaraswamy
Graphics Aditi Gajjar
Lead Technical Editor Sweny M. Sukumaran
Production Coordinator Technical Editor
Manu Joseph
Nitee Shetty Cover Work Manu Joseph
www.it-ebooks.info
About the Author Kerri Shotts has been programming since she learned BASIC on her Commodore 64.
She earned her degree in Computer Science and has worked as a Test Engineer and Database Administrator. Now, a Technology Consultant, she helps her clients with custom websites, apps (desktop and mobile), and more. When not at the computer, she enjoys photography and taking care of her aquariums.
www.it-ebooks.info
About the Reviewers Steve Husting has been involved in the creation of iPhone and Android apps for several
years. During daytime he helps manage the website for his employer’s company and at night he creates iPhone and Android apps to publish his Christian works for the public. He keeps up a hybrid app blogging website, , to publish his findings and store his notes about all things, PhoneGap/Cordova-related. He met the author of this book on the PhoneGap Google Groups forum, and was deeply appreciative of the breadth of her knowledge and ability to convey it to others.
Johnathan Iannotti is a software engineer and geek on an epic journey of life. He’s loved technology since he was young, writing Atari BASIC programs and surfing BBS’s into the morning hours. Over the years, his passion for technology evolved with the web and later into mobile apps built with both native and web technologies.
His experience spans the financial, healthcare, and military industries. He has held positions
with the federal government, digital agencies, medical manufacturers, EMR providers, and financial institutions throughout North America. He is also a Combat Veteran having served multiple tours of duty and almost a decade in the U.S. Army. He spends his free time innovating, creating Arduino gadgets, mobile apps, and riding his motorcycle through the Texas Hill Country. You can follow him on Twitter @notticode or visit his website at www.johnforhire.com.
www.it-ebooks.info
Tony Pye has over 10 years of experience in producing web-based solutions.
He strives to keep ahead of rapidly evolving web technologies in order to be able to offer innovative solutions. His passion is for matching the business goals with innovative use of technology. As head of digital production at INK Digital Agency, guiding clients through the complex digital world and integrating digital marketing with internal business systems is his specialty. Liaising with the creative and user experience team members, meeting clients, presenting ideas, and help define goals is just part of his normal day at INK. Some of the solutions he has helped to produce have delivered exciting results for companies including Ballymore, Morrisons, Renault, Tarmac, Aviva, LA fitness, and the University of Leeds. He has also worked on a number of other books as the technical reviewer, including Pro HTML5 Programming, Apress and The Definitive Guide to HTML5 WebSocket, Apress (not yet published). I’d like to thank my beautiful wife for her support and patience with me during the often long nights. Her fantastic coffee-making skills were certainly put to great use. Thanks darling!
www.it-ebooks.info
www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books.
Why Subscribe? ff
Fully searchable across every book published by Packt
ff
Copy and paste, print and bookmark content
ff
On demand and accessible via web browser
Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
www.it-ebooks.info
www.it-ebooks.info
Table of Contents Preface Project 1: Let's Get Local!
What do we build? Designing the app – UI/interactions Designing the data model Implementing the data model Implementing the start view Implementing our game view Implementing the end view Putting it all together Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge
Project 2: Let's Get Social!
What do we build? Designing the app – UI/interaction design Designing the app – the data model Implementing the data model Configuring the plugins Implementing the social view Implementing the tweet view Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge
Project 3: Being Productive
1 9
9 14 20 23 34 41 54 58 67 68
69
69 72
76 77 86 93 101 108 108
109
What do we build? Designing the user interface Designing the data model Implementing the data models
109 110 113 115
www.it-ebooks.info
Table of Contents
Implementing documents view Implementing the file view Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge
125 136 141 141
Project 4: Let's Take a Trip
143
Project 5: Talking to Your App
171
Project 6: Say Cheese!
207
Project 7: Let's Go to the Movies!
235
What do we build? Designing our UI and the look and feel Designing our data model Implementing our data model Changing our document manager Implementing our map view Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge What do we build?
Designing the user interface and the look and feel Designing the data model Implementing the data model Implementing gesture support Implementing the main view Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge What do we build? Designing the user interface and the look and feel Designing the data model Implementing the document view Implementing the image view Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge What do we build? Preparing for the video thumbnail plugin Implementing the video thumbnail plugin for iOS Implementing the video thumbnail plugin for Android Integrating with the video thumbnail plugin Implementing recording and importing of video Implementing video playback
Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge
259 260
Project 8: Playing Around
261
Project 9: Blending In
293
Project 10: Scaling Up
317
Appendix A: Quick Design Pattern Reference
339
What do we build? Designing the game Implementing the options view Generating levels Drawing to the canvas Keeping up Performing updates Handling touch-based input
Handling the accelerometer Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge What do we build? Installing the plugins Adding the navigation bar Adding the tab bar Adding the ActionSheet Adding the message box Adding the picker Adding the e-mail composer Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge What do we build? Designing the scaled-up UI Implementing the scaled-up UI Designing the split-view UI Implementing the split-view UI Game Over..... Wrapping it up Can you take the HEAT? The Hotshot Challenge The navigation list The grid Carousel 1 Carousel 2
The login screen The sign-up form The table The list of choices Doing things in bulk Searching Some things to keep in mind Summary
344 346 347 349 350 351 353 354
Appendix B: Installing ShareKit 2.0 Index
iv
www.it-ebooks.info
355 365
Preface Developing apps for mobile devices can be done using many different approaches and languages. Many apps are developed natively; meaning that they are developed in Java, Objective C, or some other language natively understood by the SDK available for the device. While native development allows the greatest flexibility and performance, the problem arises when you want to move an app from one platform to another: suddenly you're writing the app nearly from scratch. Then if you want to move to another platform, the same thing occurs. There's got to be a better way! All current mobile platforms support the idea of web apps. These are applications coded entirely in HTML and JavaScript. For simple apps, or for apps that don't need to interact with the device's capabilities, this works just fine. But the moment you need to access the file system, work with the camera, and so on, you start needing more access to the device. This is where PhoneGap comes in. PhoneGap (built on Cordova) wraps your HTML and JavaScript with just enough of a native app to let your web app feel more at home on the device. This wrapper is different for each platform, but exposes common capabilities in a consistent way. This helps you to write less code across multiple platforms. Since PhoneGap is wrapping your HTML and your JavaScript in a native shell, you also gain the ability to submit your app to the platform's app store—something you can't do with just a simple web app. Keep in mind, though, that most app stores want your app to look and feel something like a native app, and some are more strict than others when it comes to how the app should look and feel. Furthermore, don't just wrap your existing website that is hosted on some other server—many app stores will reject these kind of apps. Your app needs to have local HTML and JavaScript that supports the UI and interacts with the device. Which is where this book comes in. While we're using PhoneGap as the shell and the interface to some of the more interesting device abilities, we're not just repeating the PhoneGap documentation, either. Instead, there are full apps; each one designed to take
advantage of one or more features of the device, yes, but also fully functioning apps.
www.it-ebooks.info
Preface This book will hopefully show you how to take PhoneGap and make interesting, even exciting apps that are also cross platform. While we focus only on iOS and Android, the techniques within this book can be easily extended to BlackBerry, Windows Phone, and others with minor modifications.
What this book covers Project 1, Let's Get Local!, introduces us to PhoneGap with a simple quiz game. We'll also be
introduced to app localization by making the game available in English as well as in Spanish. We'll also be introduced to the simple framework we'll be using for the rest of the book. Project 2, Let's Get Social!, helps us develop a simple social app that displays feeds from
select Twitter accounts. We'll cover plugin installation into PhoneGap, for when we need access to native functionality that PhoneGap doesn't supply. Project 3, Being Productive, introduces us to an app, which like most apps needs to work
with the file system for persistent data storage. It is a simple note-taking app and will allow us to fully explore creating, renaming, copying, and deleting files. Project 4, Let's Take a Trip, helps us build an app that records the location of a user over a given
period of time. This will require access to the GPS functionality of the device. We'll also need to use Google Maps. We'll build further on the file management introduced in Project 3. Project 5, Talk to Your App, helps us create an app that will record voice memos, and allow
the user to play them back at will. Along the way we'll integrate with PhoneGap's audio capture and playback APIs.
Project 6, Say Cheese!, covers how to display thumbnails in a memory-efficient manner as
display and capture of media is critically important in most apps. We'll also interface with the device's camera and photo gallery.
Project 7, Let's Go to the Movies!, is much like Project 6, only here we're dealing with video.
We'll be introduced to playing video on iOS and Android (each very different), and we'll also be tasked with recording video. Finally, we'll write our first plugin to extract a thumbnail from the video for display in the app. Project 8, Playing Around, introduces us to a simple game that uses the HTML5 canvas to play
a simple game, as there are plenty of apps that do something important, sometimes we just want to have fun. We'll also work with the device's accelerometer. Project 9, Blending In, takes an app previously developed and applies native components
on to it so that it looks and feels more like a native app, because sometimes we just want to blend in. While this project is tailored specifically for iOS, you can use the concepts for other platforms. 2
www.it-ebooks.info
Preface
Project 10, Scaling Up, introduces us to the concept of detecting a tablet, since so far each
app in this book has been tailored for a phone-sized device but tablets are quite prolific as well. We will also get acquainted with the common design patterns used to scale our app up to a tablet-sized device. Appendix A, Quick Design Pattern Reference, covers some of the common design patterns
used in mobile apps.
Appendix B, Installing ShareKit 2.0, covers all the steps necessary to integrate ShareKit 2.0
with with your projects, because integrating it with iOS can get a bit painful at times.
What you need for this book To build/run the code supplied for the book, the following software is required (divided by platform where appropriate): Windows
Linux
OS X
For iOS Apps IDE
XCode 4.5+
OS
OS X 10.7+
SDK
iOS 5+
For Android Apps IDE
Eclipse 4.x Classic
Eclipse 4.x Classic
Eclipse 4.x Classic
OS
XP or newer
Any modern distro supporting Eclipse and Android SDK— Ubuntu, RHEL, and so on.
OS X 10.6+ (probably works on lower versions)
Java
1.6 or higher
1.6 or higher
1.6 or higher
SDK
Version 15+
Version 15+
Version 15+
Apache Cordova / PhoneGap
2.2
2.2
2.2
Plugins
Current
Current
Current
Version Control*
Git (Appdx B)
Git (Appdx B)
Git (Appdx B)
For All Platforms
* Used only for installation of the ShareKit 2.0 plugin in Appendix B.
3
www.it-ebooks.info
Preface Websites that can be useful for downloads are as follows: ff
Xcode: /> ff
iOS SDK: /> ff
Eclipse: /> ff
Android SDK: /> ff
Apache Cordova/PhoneGap: /> ff
Plugins: /> ff
Git: /> Who this book is for This book is for any developer who has a good sense of how to develop with HTML and JavaScript but wants to move into mobile app development. The developer should know how to write HTML and have a reasonable understanding of JavaScript. The developer should also be comfortable with setting up a development environment such as Eclipse or Xcode. This book is also for any native developer who is looking for a way to create apps that can span multiple platforms with limited modifications. PhoneGap is a great tool with which you can build a single HTML/JavaScript codebase that works across many platforms. The examples in this book specifically use PhoneGap 2.2.
Conventions In this book, you will find several headings appearing frequently. To give clear instructions of how to complete a procedure or task, we use:
What do we build? This section explains what you will build.
What does it do? This section explains what the project will achieve.
4
www.it-ebooks.info
Preface
Why is it great? This section explains why the project is cool, unique, exciting, and interesting. It describes what advantage the project will give you.
How are we going to do it? This section explains the major tasks required to complete your project. ff
Task 1
ff
Task 2
ff
Task 3
ff
Task 4, and so on
What do I need to get started? This section explains any pre-requisites for the project, such as resources or libraries that need to be downloaded, and so on.
Task 1 This section explains the task that you will perform.
Getting Ready This section explains any preliminary work that you may need to do before beginning work on the task.
Getting on with it This section lists the steps required in order to complete the task.
What did we do? This section explains how the steps performed in the previous section allow us to complete the task.
What else do I need to know The extra information in this section is relevant to the task.
5
www.it-ebooks.info
Preface In this book, you will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "The addTranslation method adds a translation to a specific locale." A block of code is set as follows: self.addAnswer = function( theAnswer ) { self.answers.push ( theAnswer ); return self; }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: <div class="navigationBar"> <div id="gameView_title"></div> id="gameView_backButton" style="left:10px"></button> </div>
New terms and important words are shown in bold. Words that you see on the screen,
in menus or dialog boxes for example, appear in the text like this: " To the left of the text is a Back button." Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
6
www.it-ebooks.info
Preface
Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code You can download the example code files for all Packt books you have purchased from your account at . If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.
Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting />submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from /> 7
www.it-ebooks.info
Preface
Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.
8
www.it-ebooks.info
Project 1 Let's Get Local! There are a lot of languages in the world, and chances are good that you want your app to
have the widest possible use and distribution, which means that you will need to provide your app with the ability to be multilingual. This can be a thorny task; a lot goes in to localization, translations, currency formats, date formats, and so on. But thankfully, there are some very smart people out there who have already worked through a lot of the pain involved. Now it's up to us to put that work to good use.
What do we build? The project that we will create is a simple game entitled Quiz Time! The game will essentially ask the player ten random questions in their native language and then tally and present their score when the game is finished. At the end, the app will ask the user if they want to try again as well. The app itself will serve to introduce you to creating mobile apps using a simple framework named YASMF (Yet Another Simple Mobile Framework). There are a multitude of fantastic frameworks out there (jQuery Mobile, jQuery Touch, iUI, Sencha Touch, and so on.), but the point of this book isn't to show you how to use a particular framework; rather, the point is to show you how to use PhoneGap to do some amazing things. The framework you choose to use ultimately doesn't really matter that much—they all do what they advertise—and our using a custom framework isn't intended to throw you off-kilter in any fashion. The main reason for using this particular custom framework is that it's very lightweight and simple, which means the concepts it uses will be easy to transfer to any framework. For more information regarding the framework, please visit /> www.it-ebooks.info
Let's Get Local! The app itself will also serve as a foundation to creating localized apps in the future. Localization is absolutely critical to get right, even in the beginning stages of development, which is why we start with it here, and why we assign it such importance. In essence, this first project is intended to make the rest of your app development career easier.
What does it do? As an app, Quiz Time! is pretty simple. There are only three screens, and only one of them is remotely complex. The game has ten built-in questions that it will randomly ask of the player. If the question is correct, the player is notified, and their score is increased by an arbitrarily large number. This is to show that we correctly handle the display of numbers in the player's locale. If the question is incorrect, we also notify the user, and then decrement their score. If they get enough questions wrong, they'll end up in negative territory, which is another great test for our localization skills. Once the game is over, we'll display the score and the date to the player, along with the opportunity to try again. If the player does elect to try again, we'll reset everything and start the game over.
Why is it great? You'll be primarily learning two things: building a simple game in PhoneGap, and localizing that app from the very beginning. A lot of projects forget about localization until near the end of the project, and then the poor developers find out that it is very difficult to shoehorn localization in after most of the project has already been developed. For example, the space assigned to some text might turn out to be too small for certain languages, or the images used as buttons or other widgets might not be large enough to hold the localized text. The app itself might crash in a certain language because it didn't expect to receive any non-English characters. By implementing localization at the start of your app development, you'll be saving yourself a lot of effort down the road, even if the first release of your app is only localized to one locale. You'll often see the word Cordova in our code examples in this book. PhoneGap was recently acquired by Adobe and the underlying code was given to the Apache Incubator project. This project is named Cordova, and PhoneGap utilizes it to provide its various services. So if you see Cordova, it really means the same thing for now.
10
www.it-ebooks.info
Project 1
How are we going to do it? We're going to follow the typical development cycle: design, implement, and test the app. Our design phase won't just include the user interface, but also the data model, that is, how our questions are stored and retrieved. The implementation will focus on our three stages of the app: the start view, the game view, and the end view. After implementation, we'll test the app not only to make sure it properly handles localization but also to make sure that the game works correctly. Here's the general outline: ff
Designing the app, UI/interactions
ff
Designing the data model
ff
Implementing the data model
ff
Implementing the start view
ff
Implementing the game view
ff
Implementing the end view
ff
Putting it all together
What do I need to get started? First, be sure to download the latest version of PhoneGap from />download, currently 2.2.0 (as this was being written), and extract it to the appropriate directory. (For example, I use /Applications/phonegap/phonegap220.) Make sure that you have also installed the appropriate IDEs (Xcode for iOS development and Eclipse for Android development). Next, download the latest version of the YASMF framework from />photokandyStudios/YASMF/downloads, and extract it anywhere. (For example, I used my Downloads folder.) If you want a copy of the projects for this book in order to look at, or to avoid the following project-creation steps, you can download them at />photokandyStudios/phonegap-hotshot. Next, you need to create a project for the various platforms you intend to support. Here's how we create both projects at once on Mac OS X. The commands should translate to Linux and Android-only projects with a little modification, and the same should apply to creating Android projects on Windows with some additional modification. For the following steps, consider $PROJECT_HOME to be the location of your project, $PHONEGAP_HOME to be the location where you installed PhoneGap, and $YASMF_DOWNLOAD to be the location where you extracted the YASMF framework. 11
www.it-ebooks.info
Let's Get Local! The following steps are just the steps that I use when setting up a project. You can, of course, structure it however you would like, but you'll need to make any modifications with regards to the file references and the likes on your own.
The following steps assume that you have downloaded PhoneGap (Cordova) 2.2.0. If you download a more recent version, the following steps should work with minimal modification: Downloading the example code You can download the example code files for all Packt books you have purchased from your account at . If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.
1. Use the following code snippet: mkdir $PROJECT_HOME cd $PROJECT_HOME mkdir Android iOS www cd $PHONEGAP_HOME/lib/android/bin ./create $PROJECT_HOME/Android/QuizTime com.phonegaphotshot. QuizTime QuizTime cd $PHONEGAP_HOME/lib/ios/bin ./create $PROJECT_HOME/iOS com.phonegaphotshot.QuizTime QuizTime cd $PROJECT_HOME mkdir www/cordova cp Android/QuizTime/assets/www/cordova-2.2.0.js www/cordova/ cordova-2.2.0-android.js cp iOS/www/cordova-2.2.0.js www/cordova/cordova-2.2.0-ios.js cd Android/QuizTime/assets
rm –rf www ln –s ../../../www cd ../../../iOS rm –rf www ln -s ../www cd .. cd www cp –r $YASMF_DOWNLOAD/framework . mkdir images models views style cd .. cd Android/QuizTime/src/com/phonegaphotshot/QuizTime edit QuizTime.java Change "index.html" to "index_android.html" Save the file. cd $PROJECT_HOME/iOS/QuizTime