it 7a

profileankitar
chapter11book.pdf

11 Getting Started with PhoneGap

WHAT’S IN THIS CHAPTER?

! History of PhoneGap

! Di! erences between HTML5 and PhoneGap

! Getting a development environment set up

! Implementing the Derby App

PhoneGap is an open source set of tools created by Nitobi Solutions (now part of Adobe) that enables you to create mobile applications for multiple devices by utilizing the same code. PhoneGap is a hybrid mobile application framework that allows the use of HTML, CSS, and JavaScript to write applications that are based on the open standards of the web. These applications also have access to the native functionality of the device. PhoneGap has been downloaded more than 600,000 times, and more than 1,000 apps built with PhoneGap are available in the respective app stores, which makes PhoneGap a viable solution for creating cross-platform mobile apps.

HISTORY OF PHONEGAP PhoneGap was started at the San Francisco iPhone Dev Camp in August 2008. iOS was shaping up to become a popular mobile platform, but the learning curve for Objective-C was more work than many developers wanted to take on. PhoneGap originally started as a headless browser implementation for the iPhone. Because of the popularity of HTML/CSS/JavaScript, it was a goal that this project use technologies with which many developers where already familiar.

Based on the growing popularity of the framework, in October 2008 Nitobi added support for Android and BlackBerry. PhoneGap was awarded the People’s Choice award at the Web2.0 Expo Launch Pad in 2009, which was the start of developers recognizing PhoneGap as a valuable mobile development tool. PhoneGap version 0.7.2 was released in April 2009, and was the fi rst version for which the Android and iPhone APIs were equivalent.

c11.indd 309c11.indd 309 28/07/12 6:08 PM28/07/12 6:08 PM

310 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

In September 2009 Apple approved the use of the PhoneGap platform to build apps for the iPhone store. Apple required that all PhoneGap apps be built using at least version 0.8.0 of the PhoneGap software. In July 2011, PhoneGap released version 1.0.0.

WHY USE PHONEGAP? PhoneGap enables you to leverage your current HTML, CSS, and JavaScript skill sets to create a mobile application. This can greatly speed up development time. When you develop for multiple platforms using PhoneGap, you can reuse the majority of the code you have written for the mobile project, further reducing development costs. It isn’t necessary to learn Java, C#, and Objective-C to create an applica- tion with PhoneGap that can target iPhone, Android, BlackBerry, and Windows Phone 7.

If you fi nd native functionality missing from PhoneGap, you can extend the functionality of the PhoneGap platform using native code. With the PhoneGap add-in structure, you can create an add-in using the native language of the device and a JavaScript API that will call the native plug-in you created. Cross-platform development enables developers to maximize the amount of resources they are able to share. As the iOS and Android user base grows, this concept becomes more important.

WHO IS USING PHONEGAP? Adopting a nonnative framework can be scary for a variety of reasons, such as stability and feature parity. Oftentimes, seeing other large projects created with the same framework will help alleviate some worries you may have. PhoneGap has recently released an updated showcase of applications built on its technology. Notable applications include an iOS application called METAR Reader, a cross-platform tool from Logitech for controlling its Squeezebox player on Android, iPad, or iPhone, and the offi cial Android Wikipedia app.

METAR Reader METAR Reader (http://www.METARReader.com) is a website for searching for and translating the Meteorological Terminal Aviation Routine Weather Report (METAR) weather data from airports and meteorological sites. The iOS app takes the branded interface of the METARReader.com website and ties into all the functionality the device can offer. Don’t know your local airport’s FAA identifi er? Use your phone’s GPS to fi nd nearby airfi elds. You can then request their METAR information and convert it to human-readable format using this tool. The METAR Reader is currently available in the Apple iOS App Store. Figure 11-1 shows the clean UI that was created in PhoneGap for the METAR app. FIGURE 11!1: METAR Reader PhoneGap app

c11.indd 310c11.indd 310 28/07/12 6:08 PM28/07/12 6:08 PM

Logitech Squeezebox Controller Logitech Squeezebox is a network music player. The entire line of products can be controlled remotely from this multiplatform app. With a consistent look and feel between iOS and Andriod, this application leverages the quick deployment power of PhoneGap. The interfaces are nearly identical while still affording for the differences in screen resolu- tion and platform idiosyncrasies. Figure 11-2 shows the interface for the Squeezebox controller.

Wikipedia It really says something when a site like Wikipedia uses PhoneGap for its platform of choice for a mobile application. Because the appeal of Wikipedia has always been its use of hypertext, breaking that feel is no different than changing a brand. Simplicity expressed through text while still being a self-contained application is shown in Figure 11-3.

The next section discusses the differences between how PhoneGap works with the HTML5 standard and how HTML5 behaves on the web.

DIFFERENCES BETWEEN PHONEGAP AND HTML5

Because PhoneGap uses HTML5 as its base, it has access to any HTML5 features that are available in the web framework for the device that is running the application. One of the differ- ences between PhoneGap and HTML5 is in the additional device interactions that are available in PhoneGap. These features can involve anything that talks to the bare metal of the device (sensors specifi cally), or more of a logical solution such as Push Notifi cations or In App Purchases. Another difference between PhoneGap and HTML5 is that PhoneGap implements the fea- tures the same way across the different devices, so that accessing the GPS function is handled with the same JavaScript for all PhoneGap devices. It doesn’t matter if you are using the iPhone, Android, BlackBerry, or Windows Phone 7 GPS functions; the calls to get the data from the GPS are the same. The other difference between a PhoneGap app and HTML5 is that an application built with PhoneGap is compiled to a native app on the device, and can be used on the device without the Internet.

FIGURE 11!2: Logitech Squeezebox PhoneGap app

FIGURE 11!3: Wikipedia PhoneGap app

Di! erences between PhoneGap and HTML5 " 311

c11.indd 311c11.indd 311 28/07/12 6:08 PM28/07/12 6:08 PM

312 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

GETTING THE TOOLS YOU NEED Even though PhoneGap applications are created using HTML, CSS, and JavaScript, you still need to have the native environments and SDKs installed for the platforms for which you want to develop. If you want your PhoneGap app to run on iOS, you need to have a Mac and have the xCode environ- ment set up as well.

PhoneGap provides great “Get Started” pages for each platform. The documentation provided within the interface will be everything you need to get up and running with PhoneGap. The interface shown in Figure 11-4 makes it easy to fi nd resources as you need them. To get started with PhoneGap, download the PhoneGap SDK at http://phonegap.com/download.

FIGURE 11!4: The PhoneGap start page for iOS

Installing PhoneGap for iOS To develop PhoneGap apps for the iOS platform, you must install xCode and the iOS SDK. Chapter 7 discusses installing xCode and the iOS in depth.

c11.indd 312c11.indd 312 28/07/12 6:08 PM28/07/12 6:08 PM

Getting the Tools You Need " 313

Installing the PhoneGap Template With PhoneGap downloaded and unarchived, navigate to the iOS directory of the extracted directo- ries and run the PhoneGap .pkg installer shown in Figure 11-5.

FIGURE 11!5: The PhoneGap iOS package

Creating Your First iOS PhoneGap Project With the PhoneGap template installed, launch xCode and select Application from the iOS section, then select PhoneGap-based Application as shown in Figure 11-6.

FIGURE 11!6: Creating a PhoneGap application

c11.indd 313c11.indd 313 28/07/12 6:08 PM28/07/12 6:08 PM

314 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

Fill out the project template as shown in Figure 11-7:

! Product Name: Name of your application.

! Company Identifi er: This needs to be unique. Once you have distributed your application, you cannot change this because it will break your ability to upgrade the application.

FIGURE 11!7: Selecting names for your PhoneGap project

Next, run the project. Click the run button in the top-right corner of xCode. This generates the www resources directory, but sometimes the www directory is not created automatically. If your application has thrown an error, open your project folder in Finder and drag the www folder to your target application project.

Make sure to select Create Folder References for any added directories. Once you have done this, run your application again and it will display the test page for the application.

Installing PhoneGap for Android To develop PhoneGap apps for the Android platform, you must install Eclipse and the Android SDK. Chapter 6 discusses installing Eclipse and Android in depth.

Creating Your First Android PhoneGap Project In Chapter 6 you learned how to create an Android application. PhoneGap is an extension of an Android app. To do this with Eclipse open, choose Create Android Application from the New Project wizard as shown in Figure 11-8.

c11.indd 314c11.indd 314 28/07/12 6:08 PM28/07/12 6:08 PM

Getting the Tools You Need " 315

Once you create the application you must copy some resources from the PhoneGap package into your application. In the root directory of the project, create two new directories named libs and assets/www.

After you create the directories, copy the following fi les:

! Copy phonegap.js from your PhoneGap zip fi le that was down- loaded earlier to assets/www.

! Copy phonegap.jar from your earlier PhoneGap download to /libs.

! Copy the xml folder from your earlier PhoneGap download to /res.

The directory structure should look similar to Figure 11-9.

FIGURE 11!8: Creating a new Android project

FIGURE 11!9: Default application after adding resources

c11.indd 315c11.indd 315 28/07/12 6:08 PM28/07/12 6:08 PM

316 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

To get the PhoneGap framework to build correctly, you now need to make some code changes:

! Instead of extending your class from the Android Activity class, change your class to extend from the Phone Gap DroidGap.

! Replace the setContentView() line with super.loadUrl(“file:///android_asset/www/ index.html”);.

! Add import com.phonegap.*;.

This may still result in an error. You will need to add the phonegap.jar fi le into your build path. Right-click phonegap.jar in your libs directory and select Build Path. Then remove import android.app.Activity;.

The Android PhoneGap app should look similar to Figure 11-10.

FIGURE 11!10: Application after PhoneGap code changes

Right-click AndroidManifest.xml, select Open With # Text Editor, and add the following Android permissions:

<uses-permission android:name=”android.permission.CAMERA” /> <uses-permission android:name=”android.permission.VIBRATE” />

c11.indd 316c11.indd 316 28/07/12 6:08 PM28/07/12 6:08 PM

Getting the Tools You Need " 317

<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” /> <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” /> <uses-permission android:name=”android.permission.ACCESS_LOCATION_EXTRA_COMMANDS” /> <uses-permission android:name=”android.permission.READ_PHONE_STATE” /> <uses-permission android:name=”android.permission.INTERNET” /> <uses-permission android:name=”android.permission.RECEIVE_SMS” /> <uses-permission android:name=”android.permission.RECORD_AUDIO” /> <uses-permission android:name=”android.permission.MODIFY_AUDIO_SETTINGS” /> <uses-permission android:name=”android.permission.READ_CONTACTS” /> <uses-permission android:name=”android.permission.WRITE_CONTACTS” /> <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /> <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” /> <uses-permission android:name=”android.permission.GET_ACCOUNTS” /> <uses-permission android:name=”android.permission.BROADCAST_STICKY” />

You are adding all of these permissions so that your application is afforded everything that PhoneGap supports in Android. Generally you would add only the permissions you need at the time you are creating the app, but PhoneGap wants to limit confi guration to project start as opposed to as you go.

The last step in this process is to add an index.html fi le in your assets/www folder with the following content:

<!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> <script type=”text/javascript” charset=”utf-8” src=”phonegap-1.4.1.js”> </script> </head> <body> <h1>Hello World</h1> </body> </html>

Installing PhoneGap for Windows Phone 7 To develop PhoneGap apps for Windows Phone 7, you must install Visual Studio and the Windows Phone SDK. Chapter 8 discusses installing Visual Studio and the Windows Phone SDK in depth.

With the Windows Phone SDK installed, navigate to the Windows Phone directory and copy the PhoneGapStarter.zip fi le to your templates folder located at C:\Users\username\Documents\ Visual Studio 2010\Templates\ProjectTemplates\Silverlight for Windows Phone as shown in Figure 11-11.

Open Visual Studio and create a new PhoneGapStarter project as shown in Figure 11-12.

c11.indd 317c11.indd 317 28/07/12 6:08 PM28/07/12 6:08 PM

318 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

FIGURE 11!11: Visual Studio template directory

FIGURE 11!12: PhoneGapStarter project

c11.indd 318c11.indd 318 28/07/12 6:08 PM28/07/12 6:08 PM

Getting the Tools You Need " 319

Build the application by pressing F5 and the project should run in the emulator as shown in Figure 11-13.

FIGURE 11!13: PhoneGap in Windows 7 emulator

PhoneGap Tools and IDE Because PhoneGap apps are created using HTML, CSS, and JavaScript, developers are not restricted to the recommended mobile platform IDEs. Every developer and designer has their own set of tools they like to use when creating HTML, CSS, and JavaScript that will work well in the development cycle of PhoneGap apps.

TextMate and Notepad++ The most basic tools that you can use to create a PhoneGap app are text editors. TextMate is a text editor for the Mac, and Notepad++ is a text editor for a Windows computer. Because PhoneGap applications use HTML and JavaScript, a text editor is a tool that can be used across platforms. If you are creating an application for iPhone and Android you can create your code in TextMate.

c11.indd 319c11.indd 319 28/07/12 6:08 PM28/07/12 6:08 PM

320 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

If you are creating your application for BlackBerry, Windows Phone 7, or Android on Windows you can use Notepad++. Using the same editor for multiple platforms gives you consistency while editing. Both TextMate and Notepad++ offer syntax highlighting and code folding.

You can’t build and compile using a text editor, but you can perform a great deal of the testing in a web browser or a tool such as Ripple.

Ripple Working in an IDE that is not familiar can be very frustrating and a huge waste of time. In many situations it is not acceptable to ask a designer to use xCode or Eclipse, nor would you want to. Working with tools you are comfortable with is one of the great benefi ts of working with PhoneGap. Ripple might be one such tool. You can get the Ripple emulator from http://ripple.tinyhippos .com/download. From the download page, you click Install and then click the Add to Chrome button. Once you have Ripple installed, it will place an icon in your Chrome browser’s menu bar, which will run the emulator when it is clicked.

Ripple is a mobile emulator that enables developers/designers to run HTML created for PhoneGap apps without having the platform SDKs installed. Figure 11-14 shows a PhoneGap app running in Ripple.

FIGURE 11!14: Ripple mobile environment

c11.indd 320c11.indd 320 28/07/12 6:08 PM28/07/12 6:08 PM

Getting the Tools You Need " 321

Firebug Firebug is a plug-in for the Firefox browser. You can get Firebug from https://addons.mozilla.org/en-US/ firefox/addon/firebug/. Because it is a Firefox extension, you just have to click on the Add to Firefox button. Firebug is useful for debugging HTML, JavaScript, and CSS. If you are writing a PhoneGap app, and none of your JavaScript is fi ring, it could be an indication that the JavaScript syntax is incorrect. If you load the .html page in Firefox, you can see the error in the Firebug console as shown in Figure 11-15.

Another thing that Firebug is good for is inspecting HTML elements. It enables you to see which CSS styles are being applied to that element. The element inspector also enables you to test changes to the HTML and see the effect those changes will have. Firebug also has a layout inspector that shows what the CSS layout looks like and what the margins are, as well as the borders and padding.

Dreamweaver 5.5 The power of PhoneGap is that someone who knows HTML/CSS can get a mobile app running very quickly. Adobe caught on to this early on, and understood that the people who were using its tools, such as Adobe Fireworks, to create the designs for web applications were often the same people who were implementing the designs with HTML/CSS in Dreamweaver. Adobe knew there would be value in a tool that the Dreamweaver user demographic could use to create mobile applications easily. Dreamweaver is not just a WYSIWYG (what you see is what you get) editor as many believe it to be. Dreamweaver is a powerful tool that contains a great deal of features that enable HTML/CSS implementers to deliver great products.

Just before Adobe acquired Nitobi, it bundled PhoneGap tools to assist with mobile development within Dreamweaver 5.5. Because the target audience was users who may not even know what an SDK is, Adobe made it simple to get the emulators and SDKs for iOS (Mac only) and Android on the machine.

Setting up the Mobile Environment in Dreamweaver 5.5 You can fi nd the paths to the SDKs in the Mobile Application feature found under the Site Menu settings. If you have a copy of Dreamweaver 5.5, and you have been working through this book chapter by chapter, you should have the SDKs downloaded and working, so just setting the paths to where the SDKs have been installed will do the trick.

If you are working with a machine that does not have the SDKs installed, the Easy Install button next to the Android path does exactly what the name implies: it downloads every- thing needed to run an Android application in the emulator. If you do not have the iOS SDK installed, there is a link with detailed instructions on how to do so in the Mobile Application setting. Figure 11-16 shows the SDKs confi gured and ready for use within Dreamweaver 5.5.

FIGURE 11!15: Firebug console show- ing syntax error

FIGURE 11!16: Dreamweaver 5.5 mobile framework confi guration

c11.indd 321c11.indd 321 28/07/12 6:08 PM28/07/12 6:08 PM

322 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

Creating a PhoneGap Project in Dreamweaver 5.5 After you have set the paths to the mobile frameworks, it’s just a matter of creating a new PhoneGap project within Dreamweaver 5.5. Choose Page from Sample # Mobile Starters # jQuery Mobile (PhoneGap) as shown in Figure 11-17 to create a new project.

FIGURE 11!17: New PhoneGap project

FIGURE 11!18: Running the project

After you select the project, Dreamweaver includes the JavaScript Library fi les for PhoneGap as well as jQuery and jQuery Mobile. At this point you can start adding logic to create the mobile PhoneGap application. When you are ready to see your application run in the emulator, simply select the framework under the Build and Emulate menu group under the Site Menu options as shown in Figure 11-18.

Before your mobile application can be deployed to a device or the market, you need to set some other settings such as the provisioning fi le for iOS. Specifi c application framework settings such as the Application Icon, Startup Screen Image, and Target OS are located under the Site Menu # Application option, as shown in Figure 11-19.

c11.indd 322c11.indd 322 28/07/12 6:08 PM28/07/12 6:08 PM

PhoneGap Project " 323

Dreamweaver is not the cheapest solution, but if you are used to the environment, or are looking for a rich HTML/CSS IDE, Dreamweaver is a powerful tool for creating PhoneGap applications.

With the understanding of the different development and testing environments that can be used to create PhoneGap mobile apps, you can dive PhoneGap code.

PHONEGAP PROJECT With all of the setup out of the way, you can focus on working with the tools and examining code for mobile apps created with PhoneGap. This section assumes you have a fundamental understanding of HTML, CSS, JavaScript, and jQuery and have worked with these technologies on other platforms.

Anatomy of a PhoneGap Application PhoneGap applications have three components:

! Native code: This code isn’t modifi ed (with some small exceptions, like the initial setup of an Android appli- cation and setting up permissions for Android). Depending on which platform you are working with, your directory structure will match that of the platform. Figure 11-20 shows the directory structure in iOS and Android.

! JavaScript: Residing within the www folder of the PhoneGap project, the PhoneGap JavaScript gives your code access to the native functions of the device.

! HTML/CSS: These fi les provide the UI layer of the application. The HTML, CSS, and JavaScript fi les live inside a www folder within the PhoneGap project.

FIGURE 11!19: Application settings

FIGURE 11!20: PhoneGap anatomy

c11.indd 323c11.indd 323 28/07/12 6:08 PM28/07/12 6:08 PM

324 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

Creating User Interfaces The user interface for a PhoneGap application relies on inputs and links. Every screen in PhoneGap is another HTML page. With every screen being a different HTML page, you can use anchor tags with an href to navigate between the screens. From the index page, which is the main screen for the PhoneGap application, you can create links to get to the different sections of your app. When you are creating an application to display data that you can drill into, you can list the parent data in an unordered list of links to a child page with a query string parameter to know which individual parent’s data to show. When you are on the child page, you can use the query string to drive the data of the child.

The other interaction point for a user is in the input fi elds. These fi elds allow the user to pass data to the application. This data can then be stored on the device, if it is user-specifi c data that isn’t needed by the server. Another use for the data is that it can be sent up to a web service.

Many developers promote PhoneGap as a “write once, deploy to multiple platforms” environment without modifying any code. This can be true, but each platform should have a unique UI. Although possible, deploying an app to an Android device with an iOS UI would not provide the best UI experience. It’s best to abstract business logic as much as possible from the UI, and plan for having separate UIs for the different platforms you plan to support.

Debugging You can use a combination of Ripple and Firefox with Firebug platform simulators to debug applications in PhoneGap. The fi rst thing to check when you are debugging a PhoneGap app is to make sure that your onDeviceReady JavaScript event is fi ring. The onDeviceReady event is the JavaScript function that is called when PhoneGap is working correctly with the device.

You can test to ensure the function is being called by adding an alert function in the onDeviceReady function alert(‘onDeviceReady has fired’);.

If onDeviceReady is not fi ring, open the page you are working with in Firefox so that you can inspect it in Firebug as shown in Figure 11-21.

FIGURE 11!21: Firebug syntax error

The example illustrates a line has not been correctly terminated. If you fi x that issue, you can check to make sure that no more syntax errors exist and try to run the program again. If onDeviceReady is still not fi ring, you need to make sure that you are including the PhoneGap JavaScript. Once that

c11.indd 324c11.indd 324 28/07/12 6:08 PM28/07/12 6:08 PM

PhoneGap Project " 325

is included you can try to run it again. If you are getting inside onDeviceReady, but the function isn’t running, you can wrap the call in a try/catch block to ensure that the code isn’t throwing an error. Then when you run the code, you will see that you haven’t declared printToConsole as shown in Figure 11-22.

try{ printToConsole(‘This line wasn\’t Terminated’); } catch(err) { alert(err); }

Now you can create the printToConsole function and run the project again to see the code in action:

function printToConsole(stringToPrint){ console.log(stringToPrint); }

Figure 11-23 shows PhoneGap writing a log message to the console screen of xCode.

FIGURE 11!22: Alert showing caught JavaScript error

FIGURE 11!23: Console from successful run

With the log showing, you have seen the basic steps for debugging a PhoneGap application. Start with checking the syntax of your page, then check to make sure you have included all applicable libraries, wrap your code in try/catch blocks, and use alerts and the console log to ensure that the code is producing the appropriate results.

Useful JavaScript Libraries When we all started out as developers, “do not re-create the wheel” was driven into our heads. That is a message that most developers take to heart, and they have amassed a great deal of useful tools over the years. As a web developer, these tools could be simple JavaScript libraries that allow only numbers to be entered into a text box or could be complex UI libraries that combine HTML/CSS and JavaScript to create a slick interface to enter data.

PhoneGap embraces libraries, and the developer community has created a great deal of tools to help mobile PhoneGap developers.

c11.indd 325c11.indd 325 28/07/12 6:08 PM28/07/12 6:08 PM

326 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

jQuery jQuery is a JavaScript library that is used to make DOM selection, manipulation, event handling, and AJAX interactions easier for web development. Because PhoneGap is HTML5-based, the jQuery library is very useful. With jQuery you can select an individual element on the page so that you can manipulate it. jQuery is used in PhoneGap to bind events to buttons.

iScroll One of the libraries used in most PhoneGap applications is the iScroll library. The iScroll library is useful for both iPhone and Android projects. This library enables you to set a scrolling area on part of the mobile screen, and have only that portion of the screen scroll. Without iScroll, PhoneGap apps scroll over the entire screen, and any headers or footers will scroll out of sight. When the header and footer scroll out of sight, it’s a good sign that app was not created natively.

PhoneGap iPhone apps without iScroll have a rubber band effect (where the app bounced up and down like a stretched-out rubber band), which can be noticed any time the phone is scrolled. To set up iScroll you set a wrapper div and a scroller div. The scroller div is necessary because only the fi rst element inside the wrapper div is actually scrolled. The iScroll library also enables you to add pinch to zoom (UI gestures where the thumb and index fi gure are “pinched” together on a screen to cause a zoom effect) support. This lets you set an area that can be zoomed, as well as setting a max zoom, a min zoom, a starting zoom, and an area that is prezoomed. Another feature of the iScroll library is a pull to refresh (UI gesture where the top of the app is pulled down, and the content on the page is refreshed). This enables you to set up calls that happen when the screen is pulled down, which can be a useful way to access more information in a list of information.

The HTML for a scroller is not very complicated. You need a wrapper div which will hold the scrolling area. Because iScroll scrolls only the fi rst element inside the wrapper, you also need a div inside the wrapper that will be scrolled. The inner div is where the long list of elements will be held, which are inside the unordered list:

<body onload=”onLoad()”> <div id=”wrapper”> <div id=”scroller”> <ul></ul> </div> </div> </body>

The JavaScript for the scroller requires two things. The fi rst is that you need to stop the native scrolling events. You do this by adding an event listener to the touchmove event and calling preventDefault();. The second piece is to create the scrollView by calling iScroll and passing it the ID of the wrapper element:

<script type=”text/javascript” charset=”utf-8”> var scrollView;

function onLoad() { document.addEventListener(‘touchmove’, function (e) { e.preventDefault(); }, false); document.addEventListener(“deviceready”, onDeviceReady, false); }

c11.indd 326c11.indd 326 28/07/12 6:08 PM28/07/12 6:08 PM

PhoneGap Project " 327

function onDeviceReady() { setHeight(); //Here we are adding a list of items which will require scrolling. var list = jQuery(“#scroller”).find(‘ul’); for (var i = 0; i < 50; i++) { singleItem = “<li title=”+ i +” >Item” + i + “</li>”; list.append(singleItem); } scrollView = new iScroll(‘wrapper’, {desktopCompatibility:true}); } </script>

Use CSS to set the height of the wrapper. You can also use jQuery if you are using Android, where the devices do not have standard sizes.

var fullHeight = window.innerHeight; var mainHeight = fullHeight - 60; jQuery(‘#wrapper’).css({height: mainHeight + ‘px’ });

/*---------Scroll area code----------*/

#wrapper { height:270px; /* Of course you need to specify the object height */ position:relative; z-index:1; /* it seems that recent webkit is less picky and works anyway. */ width:100%; overflow:hidden; }

jQuery Mobile jQuery mobile is library that you can use to provide a user interface that works seamlessly across all popular mobile platforms. jQuery mobile provides tools to make it easy to format controls and layout of a mobile page. Figure 11-24 is an example of a jQuery mobile page.

This page would look identical rendered on an Android device, so the drawback of using this library is that its controls look similar to iOS controls.

Pages are laid out very semantically in jQuery mobile. jQuery mobile takes advantage of the HTML5 data-role attribute to identify sections of the page, such as header, content, and footer:

<div data-role=”page”>

<div data-role=”header”> <h1>Page Title</h1> </div><!-- /header -->

<div data-role=”content”> FIGURE 11!24: jQuery Mobile UI

c11.indd 327c11.indd 327 28/07/12 6:08 PM28/07/12 6:08 PM

328 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

<p>Page content goes here.</p> </div><!-- /content -->

<div data-role=”footer”> <h4>Page Footer</h4> </div><!-- /footer -->

</div><!-- /page -->

With the data roles set, and the jQuery mobile JS fi le included, the app renders a header and footer with a scrollable content area without any more interaction required from the developer.

Sencha Touch Sencha Touch is an MVC framework for creating HTML5 applications. It can be used with PhoneGap for iOS, Android, and BlackBerry apps. When Sencha Touch is combined with PhoneGap, it can be used to create native looking applications. To use Sencha Touch you need to get the free download from http://www.sencha.com/products/touch/. After that you can include the Sencha Touch SDK in a lib folder inside of the www folder of a PhoneGap project.

Convention for Sencha Touch projects is to have models, views, controllers, and lib folders inside the www folder of a PhoneGap project. The app folder contains the app.js fi le, which contains the launch events for Sencha Touch. Sencha projects need to wait for both the Sencha launch event and PhoneGap’s device ready event before fi ring. You can check this by setting the launched property within the Sencha launch event. Then inside the mainLaunch function, you can check to make sure the framework is loaded by checking this property as shown in the fol- lowing code.

Ext.regApplication({ name: ‘app’, launch: function() { this.launched = true; this.mainLaunch(); }, mainLaunch: function() { if (!device || !this.launched) {console.log(‘main Not Ready’); return; } console.log(‘mainLaunch’); } });

You may have noticed this calls mainLaunch twice — once on ondeviceready and once on launch, with the mainLaunch function continuing on to the second call.

You can then use this with the MVC pattern to create the data layers, and use them to display the data back to the user. From the list example in the documentation you can see the differences between the Android and the iPhone versions of the Sencha Touch application. Figure 11-25 shows an example UI created with Sencha Touch rendered in both iOS and Android. Again, notice that the UI is very similar to an iOS interface.

c11.indd 328c11.indd 328 28/07/12 6:08 PM28/07/12 6:08 PM

PhoneGap Project " 329

XUI XUI is an open source JavaScript library built specifi cally for mobile devices. It contains a subset of the functionality of jQuery, but with a much smaller footprint. Brian Leroux, who works for Nitobi on the PhoneGap project, started the XUI project in 2008. XUI provides selectors that use CSS3 style selectors. For example, to get an element in XUI you can use the following code to select the liTest item, and turn the text red:

x$(“#liTest”).css({‘color’:’red’});

XUI also gives you access to events. One of the events that you can access is the button click event, which takes a callback. You can select a button and assign a buttonPressed function to the click’s callback. The buttonPressed function executes when the button is pressed:

<body> <button id=”buttonTest” >Press For Alert</button> </body>

function onDeviceReady(){ x$(“#buttonTest”).click(buttonPressed); }

function buttonPressed(){ alert(‘Button Pressed’); }

XUI can also use transformations to make modifi cations to the CSS properties of elements on the DOM. It takes the new CSS style and applies the transformation based on the duration that is specifi ed. It also has an optional callback that is called once the transformation is completed.

x$(‘#liTest’).tween({ color:’blue’, duration:1500 }, function() { alert(‘done!’); });

XUI also has an XmlHttpRequest (XHR) function to return objects from a call to a JSON service. These calls take a request string, a callback function for success, the headers to be passed, and a callback for errors:

x$().xhr(requestString, { callback: successFunction, headers: [{name:”Accept”, value: “application/json”}], error: function(){alert(‘Error ‘);

FIGURE 11!25: iPhone Sencha list

c11.indd 329c11.indd 329 28/07/12 6:08 PM28/07/12 6:08 PM

330 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

} });

To make the call to an outside service for iPhone, you need to add the service to the external hosts in the PhoneGap.plist fi le. The easiest way to enable the external service for debugging is to add the * wildcard to the external hosts, as shown in Figure 11-26.

The data from the request string is placed on the responseText variable in the success callback. This can then be parsed with JavaScript’s eval function, which turns the XML into an array of items that can be used to get the items from the JSON response:

function successFunction(){ var dataItems = eval(“(“+this.responseText +”)”).d; for (var i = 0; i < dataItems.length; i++) { console.log(dataItems[i].Name); } }

LawnChair LawnChair is a JavaScript library that was built to allow persistent storage of data in a lightweight application. The primary target for LawnChair is mobile HTML5 applications, due to LawnChair’s lightweight nature. To use LawnChair you need to set up a data store:

var store = new Lawnchair({name:’testing’}, function(store) {});

Once you have the store, you can create an object with a key, and then place that object in the store:

var me = {key:’adam’, lastName:’Ryder’}; store.save(me);

Now that the object is stored, you can retrieve it from the store using the key:

store.get(‘adam’, function(item) { alert(item.lastName); });

This would get the object and alert the lastName item from the object. LawnChair is small; only 8 K in size. This lends itself well to being packaged in PhoneGap, because it won’t take much space on the device.

BUILDING THE DERBY APP IN PHONEGAP The idea of the Derby App is to build the same app over all of the mobile platforms covered in this book. The PhoneGap version is very similar to the other versions that you have built thus far or will build in future chapters.

FIGURE 11!26: External hosts with Item 0 Set to *

c11.indd 330c11.indd 330 28/07/12 6:08 PM28/07/12 6:08 PM

Building the Derby App in PhoneGap " 331

The requirements are to provide two pages: one that lists all the teams/leagues and one that lists all the players. When a league/team is selected, the application shows the roster for the team. When a player is selected, it shows which team the player belongs to and her number.

The fi rst thing that you want to do in the Derby App is to create a placeholder which will hold the list of all the derby teams. You set this up on the index.html page:

<div id=”wrapper”> <div id=”scroller”> <ul> </ul> </div> </div>

You have set up the wrapper with an unordered list inside of the scroller. You need to add the listener for PhoneGap’s device ready event, and make a callback to the onDeviceReady function inside the onLoad function.

You also need to add a listener to the touchmove event to prevent the default touchmove behavior. Then you can use the iScroll library to control the movement of the screen:

function onLoad() { document.addEventListener(‘touchmove’, function (e) { e.preventDefault(); }, false); document.addEventListener(“deviceready”, onDeviceReady, false); }

With the ondevice events wired up you can now request data from the derby name service. To accomplish this, create a fi le named OData.js to handle all requests to the oData Derby Names web service. This OData.js fi le will need to be included in your index.html header. The OData.js fi le has a getData function that takes a request string and a successFunction callback. The actual request is made using XUI’s XHR function, which calls the success function and passes the results from the request string to the function.

function OData() { this.getData = function (requestString, successFunction) { x$().xhr(requestString, { callback: successFunction, headers: [{name:”Accept”, value: “application/json”}], error: function(){alert(‘Error ‘); }}); };

Next, set up a DerbyService function that contains all of the service calls and builds the request strings and sends them to the OData function. The calls in the DerbyService contain functions to get the leagues and take a callback.

function DerbyService() {

this.HostName = ‘http://derbynames.gravityworksdesign.com’; this.BaseServiceUrl = this.HostName + ‘/DerbyNamesService.svc/’; this.odataService = new oData();

this.searchAllLeagues = function (successFunction) { var serviceString = this.BaseServiceUrl + “Leagues?$top=50”;

c11.indd 331c11.indd 331 28/07/12 6:08 PM28/07/12 6:08 PM

332 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

odataService = new oData(); odataService.getData(serviceString, successFunction); }; }

The onDeviceReady function calls setHeight, which is a function in your helper.js fi le and the searchAll function, which is a local function with a callback to an anonymous function that sets up the scrollView for your iScroll implementation:

setHeight(); searchAll( function(){ setTimeout(function () { scrollView = new iScroll(‘wrapper’, {desktopCompatibility:true}); }, 500); });

The searchAll function creates an instance of the DerbyService, and then calls the searchAllLeagues function of the derby service with an anonymous callback function. The anonymous callback will call another helper function to display the league data on the screen. The displayAllLeagueDataOnScreen function takes a parameter for the response from the OData service, the search string (currently empty string), and the ID of the div that will hold the results.

function searchAll(callback){ var service = new DerbyService(); service.searchAllLeagues(function(){ displayAllLeagueDataOnScreen(this.responseText, “”, “scroller”); } });

callback(); }

The displayAllLeagueDataOnScreen function uses jQuery to fi nd the list name, and removes any list items that are currently in the list. It then calls the appendAllLeagueDataOnScreen function, passing it the data, search term, and the list name:

function displayAllLeagueDataOnScreen(data, searchTerm, listName){ jQuery(“#” + listName).find(‘li’).remove(); appendAllLeagueDataOnScreen(data, searchTerm, listName); }

The appendAllLeagueDataOnScreen function calls the JavaScript eval function on the data to get an array of dataItems to work with. You also create a temporary singleItem to hold the league list item. You use jQuery again to fi nd the unordered list inside of the listName that was passed in. For every dataItem, you create a link that will go to the leagues page, league.html, which shows all of the players for that league.

After the item is created you append those items to the list. If the data item’s length is the same as the number of records you asked for, you also add a link to get more items when you scroll to the bottom of the list.

c11.indd 332c11.indd 332 28/07/12 6:08 PM28/07/12 6:08 PM

Building the Derby App in PhoneGap " 333

function appendAllLeagueDataOnScreen(data, searchTerm, listName){ var dataItems = eval(“(“+ data +”)”).d; var singleItem = “”; var list = jQuery(“#” + listName).find(‘ul’);

for (var i = 0; i < dataItems.length; i++) { singleItem = “<a href=’league.html?League=” + dataItems[i].LeagueName + “’> <li title=”; singleItem = singleItem + dataItems[i].LeagueName +” >”; singleItem = singleItem + dataItems[i].LeagueName + “</li></a>”;

list.append(singleItem); }

if(dataItems.length == 50){ if(searchTerm == “”){ singleItem = “<a href=’#’ id=’btnGetMore’ onclick=’LoadMorePushed()’>” singleItem = singleItem + “<li id=’liAddMore’>Load More</li></a>”; } else{ singleItem = “<a href=’#’ id=’btnGetMore’ onclick=’LoadMoreSearchPushed(&quot;”; singleItem = singleItem + searchTerm + “&quot;)’><li id=’liAddMore’>Load More</li></a>”; }

list.append(singleItem); } }

Figure 11-27 shows the index page rendering a list of roller derby teams.

Now that you have the leagues set up as a list of links to a league.html page, you can use CSS to change the links to look more like the native OS list items. You can set the list-style to none and the list-type to none, which will remove the bullets. When you set text-decorations to none for the anchor tabs, the links will no longer be underlined.

ul { list-style:none; padding:0; margin:0; width:100%; text-align:left; }

li { margin:5px 0; padding:3px 7px 7px 7px; border-bottom:1px solid #ddd; list-style-type:none; font-size:15px; font-weight:bold; margin-right:5px; }

FIGURE 11!27: List of derby teams rendered on an iPhone

c11.indd 333c11.indd 333 28/07/12 6:08 PM28/07/12 6:08 PM

334 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

a:link, a:visited { text-decoration:none; color:#000; font-weight:bold; }

Figure 11-28 shows what the Derby app looks like after this small amount of CSS has been added.

With the scrolling working and the list looking like a list, you can add a header to the league page. The header consists of two links with classes, which will become image links through CSS. This header will also be used on the individualList.html page, just with different classes, so that the links look different.

<div class=”header”> <a id=”btnLeague” href=’index.html’ class=”btnTwoLeft”>Leagues</a> <a id=”btnIndividuals” href=’individualList.html’ class=”btnTwoRightSelected” >Players</a> </div>

Here is the CSS for the buttons; the images are stored inside the images directory within the www directory:

.btnTwoLeft { height:23px; width:150px; background:url(images/btn-two-left.png) no-repeat; float:left; text-align:center; font-size:14px; font-weight:200!important; color:#fff!important; font:Georgia, “Times New Roman”, Times, serif; padding:7px 0 0 0; margin:2px 0; }

.btnTwoLeftSelected { height:23px; width:150px; background:url(images/btn-two-left-selected.png) no-repeat; float:left; text-align:center; font-size:14px; font-weight:200!important; color:#fff!important; font:Georgia, “Times New Roman”, Times, serif; padding:7px 0 0 0; margin:2px 0; }

With the header added, the league screen is now starting to look like a mobile app. Figure 11-29 shows the header added to the league screen.

FIGURE 11!28: Formatted league list displayed on an iPhone

FIGURE 11!29: Derby App with header added

c11.indd 334c11.indd 334 28/07/12 6:08 PM28/07/12 6:08 PM

Other Useful PhoneGap Things " 335

There is another useful option for a list this long, and that is the ability to search. To search, you need a text box for the search term, a button to search with, and another service call for searching:

<input id=”txtSearch” type=”search” placeholder=”Search” class=”searchbar”> <button id=”btnSubmit” type=”button” class=”gobtn” label=”Go” >GO</button>

Wire up the button click event in the onDeviceReady function. This click function gets the searchCriteria from the search text box and passes that to the searchLeagues function:

jQuery(“#btnSubmit”).click(function(){ var searchCriteria = jQuery(“#txtSearch”).val(); skipCount = 50; searchLeagues(searchCriteria); });

The searchLeagues function creates a new instance of the DerbyService and calls the searchLeagues function in the service with a callback to displayAllLeagueDataOnScreen. This is the same function that you called when you displayed the unfi ltered list.

function searchLeagues(searchCriteria){ var service = new DerbyService();

service.searchLeagues(searchCriteria, function(){ displayAllLeagueDataOnScreen(this.responseText, searchCriteria, “scroller”); }); }

The searchLeagues function in the service calls the OData object with a fi lter that looks for a sub- string of the searchString that is passed in the LeagueName property:

this.searchLeagues = function (searchString, successFunction) { var serviceString = this.BaseServiceUrl + “Leagues?$top=50&$filter=\ substringof(‘” + searchString + “’,LeagueName)”;

this.odataService.getData(serviceString, successFunction); };

With the search in place, Figure 11-30 shows the completed UI for the Leagues screen in the Derby App.

With the Derby App completed, now you can take a look at some of the other useful functions in PhoneGap.

OTHER USEFUL PHONEGAP THINGS Thus far, the examples in this chapter have provided the basics for creating a PhoneGap application. This application will go out to a web service and render the data on the screen. This does not cover every possible situation you will encounter as a PhoneGap mobile developer, so we will fi nish this

FIGURE 11!30: Derby App with league search added

c11.indd 335c11.indd 335 28/07/12 6:08 PM28/07/12 6:08 PM

336 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

chapter by providing a few short examples of other common tasks you may need to accomplish when working with PhoneGap.

Pickers Pickers in PhoneGap come in two fl avors. The fi rst type of picker is a date-style picker. These pickers rely on plug-ins to function, because there isn’t a uniform date picker available to the different platforms yet. iOS 5 does support the HTML date input type. You can get the code for the date picker from https://github.com/phonegap/phonegap-plugins/tree/master/ iPhone/DatePicker. This will have the .js, .h, and .m fi les. The .h and .m fi les go into your Plugins directory. The DatePicker.js fi le belongs in your www directory. You also need to add a DatePicker key and value to the plugins section of your phonegap.plist fi le. You need to create a callback and a function that will be called during the onclick of a link.

var callbackFunction = function(date) { console.log(date.toString()); document.getElementById(“date”).innerHTML = date.toString(); } var showDatePicker = function(mode) { plugins.datePicker.show({ date: new Date(), mode: mode, //date or time or blank for both allowOldDates: false }, callbackFunction); }

The other way to create a picker, which is our recommended way, is to create a page that lists the items you want to pick from as links back to your selector. In your HTML you could have a link to a pickList page:

<a href=’pickList.html’>Choose Your Favorite Color</a>

On the pickList page you can set up the list as a series of links back to the index with the choices differentiated by the query string parameter that is passed back:

<html> <ul> <li><a href=’index.html?color=blue’>Blue</a> <li><a href=’index.html?color=green’>Green</a> <li><a href=’index.html?color=red’>Red</a> </ul> </html>

Once back on the index page you can read the query string and take action based on what it con- tains. You can use regular expressions in JavaScript to decode the query string and return the value of the query string parameter. You could add another JavaScript library to handle this, but it is quicker and easier to just write the function yourself:

function getParameterByName( name ){ name = name.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);

c11.indd 336c11.indd 336 28/07/12 6:08 PM28/07/12 6:08 PM

Other Useful PhoneGap Things " 337

var regexS = “[\\?&]”+name+”=([^&#]*)”; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return “”; else return decodeURIComponent(results[1].replace(/\+/g, “ “)); }

Once you make the call to getParameterByName you can use the information that you have in the query string:

var color = getParameterByName(‘color’); if (color != ‘’) { alert(‘You Chose: ‘ + color); }

Figure 11-31 is an example of the color picker view.

O" ine Storage Sometimes you will need to store data on the device. This could be because the business rules for your app require offl ine usage, or it could be just a matter of saving a few settings such as username and password. This section shows you the different techniques you can use to store data offl ine so that it can be retrieved when the user is not connected to the web. Offl ine storage also allows you to store settings on the device for your user.

Web SQL If you have a lot of data that needs to be stored, one of the better ways to store that data is in a database. PhoneGap provides a mechanism to create, maintain, and retrieve records from an internal database. The fi rst thing you need to do to use the database is to open it. You must do this after PhoneGap’s deviceready event has been fi red. The following code creates or opens a database named PlayerDemo with a version of 1.0 and a display name of Player Demo. The 10000 is the size of the database in bytes.

function onDeviceReady() { var db = window.openDatabase(“PlayerDemo”, “1.0”, “Player Demo”, 10000); }

Now that you have a database you can run transactions against it. You do that by calling the transaction function on the database, and passing in a callback function, an error callback, and a success callback. The callback function gets called with a transaction object. The fi rst thing you do is populate the database:

db.transaction(populateDB, onDBError, onDBSuccess);

FIGURE 11!31: Color picker view

c11.indd 337c11.indd 337 28/07/12 6:08 PM28/07/12 6:08 PM

338 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

This calls the populateDB function and passes the function its transaction. This means that if any of the commands in the transaction fail, the entire transaction will be rolled back. The following function creates a players table:

function populateDB(tx){ tx.executeSql(‘DROP TABLE IF EXISTS PLAYERS’); tx.executeSql(‘CREATE TABLE IF NOT EXISTS PLAYERS (id unique, number, name)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (1, 6, “Adam”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (2, 1, “Jeff”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (3, 4, “Scott”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (4, 2, “Amelia”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (5, 5, “Dave”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (6, 3, “Lauren”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (7, 7, “Ashley”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (8, 9, “Nathan”)’); tx.executeSql(‘INSERT INTO PLAYERS (id, number, name) VALUES (9, 8, “Heather”)’); }

Now that you have the database populated you can create another transaction that you can use to retrieve the data from the players table that you just created. To get the data back from a query, you call executeSQL and pass it the query, arguments, the success callback, and the error callback:

tx.executeSql(‘SELECT * FROM PLAYERS ORDER BY name’, [], onQuerySuccess, onDBError);

You can use the onQuerySuccess callback to iterate through the results and display them to the screen, as shown in Figure 11-32:

FIGURE 11!32: SQL returned to screen

c11.indd 338c11.indd 338 28/07/12 6:08 PM28/07/12 6:08 PM

Other Useful PhoneGap Things " 339

function onQuerySuccess(tx, results){

try{ var playerInfo = ‘<ul>’; var len = results.rows.length; for (var i=0; i<len; i++){ playerInfo += ‘<li><b>’ + results.rows.item(i).name + ‘</b>(‘ + results.rows.item(i).number + ‘)</li>’; } playerInfo += ‘</ul>’; jQuery(‘#divPlayers’).html(playerInfo); } catch(err){ alert(err); } }

Filesystem Storage Local storage is also available. The local storage is available as key-value pairs. To store Lansing as a favorite, you would call setItem, passing in the key (favorite) and the value (Lansing):

window.localStorage.setItem(“favorite”, “Lansing”);

This storage is persistent and will be available the next time the applica- tion is run. To retrieve the data you call getItem with the key that you are looking for. The following code retrieves the favorite item and then alerts that item, as shown in Figure 11-33:

var fav = window.localStorage.getItem(“favorite”); alert(fav);

GPS You access the GPS through PhoneGap by calling the geolocation function with a callback:

function onDeviceReady() { navigator.geolocation.getCurrentPosition(gpsSuccess, gpsFailure); }

As with all of the PhoneGap functions, the GPS functions cannot be called until the deviceready event has been fi red. The success callback returns a position object, which has a coordinates object that contains properties for latitude, longitude, altitude, accuracy, heading, and speed:

function gpsSuccess(location){ var gpsinfo = ‘<ul><li>Latitude: ‘ + location.coords.latitude + ‘</li>’; gpsinfo += ‘<li>longitude: ‘ + location.coords.longitude + ‘</li>’;

FIGURE 11!33: Local storage alert

c11.indd 339c11.indd 339 28/07/12 6:08 PM28/07/12 6:08 PM

340 " CHAPTER 11 GETTING STARTED WITH PHONEGAP

gpsinfo += ‘<li>Altitude: ‘ + location.coords.altitude + ‘</li>’; gpsinfo += ‘<li>Accuracy: ‘ + location.coords.accuracy + ‘</li>’; gpsinfo += ‘<li>Speed: ‘ + location.coords.speed + ‘</li></ul>’;

jQuery(‘#GPSInfo’).html(gpsinfo); }

There is also a failure callback that returns a positionError object. The positionError object has a code and a message property:

function gpsFailure(PositionError){ alert(PositionError.code); alert(PositionError.message); }

Accelerometer You can access the accelerometer using the accelerometer’s watchAcceleration function with a callback for the success and for errors. watchAcceleration is set to a variable and fi res on the frequency that is set in the options. The iPhone simulator does not transmit accelerometer data; however, the Android simulator does, so if you are testing without a device, the accelerometer needs to be tested on Android.

var options = { frequency: 3000 }; watch = navigator.accelerometer.watchAcceleration(successFunction, errorFunction, options); //The success function takes an acceleration object. //This object has the x, y and z change, //as well as the timestamp from when the acceleration was gathered. function successFunction(acceleration){ try{ x$(“#spanX”).html(acceleration.x); x$(“#spanY”).html(acceleration.y); x$(“#spanZ”).html(acceleration.z); x$(“#spanTime”).html(acceleration.timestamp); } catch(err) { alert(err); } }

To stop the watch from fi ring constantly, you can call the clearWatch function and pass it the watch variable to stop the watch from fi ring:

x$(‘#btnStop’).click(function(){ navigator.accelerometer.clearWatch(watch); });

Now that you have a working app you can connect the application to the markets.

c11.indd 340c11.indd 340 28/07/12 6:08 PM28/07/12 6:08 PM

Summary " 341

CONNECTING PHONEGAP TO THE MARKETS If you have been following through the book chapter by chapter, you have seen how to connect to the different markets. Because PhoneGap applications are compiled with their native frameworks, they are released to the markets in the same manner as their true native counterparts are released. Refer to the corresponding section of Chapters 6–9 for more information on connecting to the vari- ous markets.

SUMMARY PhoneGap is an easy-to-learn framework for creating cross-platform mobile applications. Everything in PhoneGap derives from the onDeviceReady listener. Once onDeviceReady fi res, you have access to the device’s native components, like the GPS, camera, or accelerometer. Leveraging your current HTML, CSS, and JavaScript knowledge also enables you to create these applications with a lower learning curve.

Because PhoneGap is cross platform, you don’t need to learn four different languages to be able to deploy your application across iPhone, Android, BlackBerry, and Windows Phone 7. Having the same codebase for all platforms can also give you a sense of parity through the different device platforms.

Now that you have created mobile applications with PhoneGap, the next chapter will show how to create Android and iPhone applications using .NET and the Mono framework.

c11.indd 341c11.indd 341 28/07/12 6:08 PM28/07/12 6:08 PM