10. Developing Mobile Games

It could easily be argued that the 2007 release of the iPhone was the genesis of mobile gaming and the “app-itization” of web content. Sales of content for mobile devices, including phones, tablets, and televisions has numbered in the billions. Although mobile games existed before, the appearance of smartphones was one of the first times that mobile devices could use the Web—the real Web—and not some watered-down version for consuming and producing content. In this chapter, we will discuss in part the dominant mobile phone operating systems, what is involved in developing for them, and some of the frameworks that work with them. Before we go into the how and why, let’s briefly discuss the platforms themselves.

Choosing a Mobile Platform

In this section, we briefly cover the capabilities and peculiarities of the dominant mobile device operating systems.

iOS

Formerly known as the iPhone OS, iOS powers most of Apple’s mobile and entertainment devices, including the iPhone, iPod Touch, iPad, and AppleTV. Considering only mobile devices, iOS has garnered approximately 16.8% of market share, at the time of this writing. iOS is a variant of the BSD-based Mac OS X optimized for touch interaction. iOS is restricted to Apple-branded devices. iOS applications that are not served by the browser are generally coded in the Objective-C programming language. The iPhone, iPod Touch, and iPad can connect to other devices using Wi-Fi and sometimes Bluetooth and CDMA/GSM cellular service. Webkit, a fork of the open-source KHTML layout engine, powers the browser experience for these devices. HTML5 is extra important to Apple because it forbids plugin technology such as Flash in its iOS devices. In addition to the iOS devices, on the desktop, Webkit is at the core of Google Chrome and Apple Safari, the third and fourth most popular desktop browsers. When it comes to implementing HTML5 standards, browsers that use Webkit have been at the forefront of the charge.

Android

Android is an operating system created by Google to run on mobile devices. Android has captured 36% of the market thanks to a multitude of carriers and device options. The first Android device launched approximately a year after the initial iPhone. One of the key differentiators between devices running Android and those running iOS is that, except in rare cases, Google doesn’t assert control over the devices and or their specifications. Native Android applications can be written in a Java syntax that can be compiled for the Dalvik virtual machine. Communications options vary by device but are equivalent to those of the iOS devices. Android and iOS devices may also contain gyroscopes for directional positioning and accelerators to infer motion in space. Thanks to Android’s open-source license, cellular carriers are free to install Android on any device or modify parts of the operating system without getting Google’s permission. This has contributed to Android’s gains in market share. A plethora of phones and tablets have emerged in the past three years spread across about five different versions of the operating system. Although this may cause some fragmentation in the capabilities of the core OS, it has less-tangible ramifications for HTML5 games. Android uses a variant of the Google Chrome web browser, which itself is derived in part from Webkit. Although some devices are still being released with the relatively ancient Cupcake and Donut versions (1.5 and 1.6, respectively), most new devices run Eclair (Android 2.0/2.1), Froyo (Android 2.2), or higher—which boast improved HTML5 support and faster JavaScript engines. Recent Android devices can also run Flash content, unlike their iOS counterparts. Because the operating system is open source, there tends to be a plethora of devices running different versions of Android. Although much hay has been made about fragmentation, at any given time, the number of versions run by a plurality of devices is generally only one or two.

WebOS

WebOS is a operating system creating by Palm, later acquired by HP, to run on mobile devices. The first devices launched in June 2009. Under Palm’s tenure, only two devices were released: the Palm Pre and the Palm Pixi/Pixi Plus. WebOS, although using Linux for its core functionality, makes use of JavaScript, HTML, and AJAX for most user-facing applications. Since the acquisition, an updated Palm Pre 2 has launched and HP has announced its intention to use WebOS for mobile phones, tablets, and printers. WebOS only accounts for a scant sliver of the market. In mid to late August 2011, HP decided to exit the hardware business and discontinued production of the Palm Pre 2 and its tablet form factor device, the Touchpad. Existing devices have been marked down to fire sale prices with many consumers seeking devices in hopes that Android will be ported to it. HP says that their exit from hardware doesn’t mean the end of WebOS. That remains to be seen.

Windows Phone 7

Last is the most recent entrant into the market, Windows Phone 7, created by Microsoft. The market share for Windows Phone 7 is somewhere below 3.3%. That figure includes Windows Mobile devices as well. The first Windows Phone 7 devices launched in late 2010. Windows Phone 7 is a break in compatibility to its predecessor Windows Mobile 6.5. Applications can be written in C# using either Microsoft’s Internet application framework Silverlight, or the more gaming focused XNA project. For our needs, Windows Phone 7 at present is a nonstarter. The included browser is a blend of features from Internet Explorer 7 and 8, which support no HTML5 elements. Bear in mind that Internet Explorer 9 beta has a more complete implementation of HTML5 features.

In mid-2011, Microsoft and Nokia brokered a deal making Windows Phone 7 the standard OS for new Nokia devices. As these devices begin to roll out, Windows Phone 7 will begin to consume the 27.4% market share held by devices running Nokia’s Symbian operating system. During that same time, Microsoft announced the “Mango” update to Windows Phone 7, which includes a mobile version of Internet Explorer 9 with HTML5 support. The update is due sometime in Fall 2011.

Flick, Tap, and Swipe: A Quick Guide to Mobile Gestures

If I take away your mouse and keyboard and give you a touch screen, you’ll need a way to communicate with the system, and mobile gestures are just how you would do that. Gestures allow you to replace the mouse with your finger. Capacitive screens (or in laymen’s terms, multitouch screens) allow you to interact with the screen using multiple fingers at one time. Multitouch screens allow you to do things that aren’t usually possible with mice, such as making a pinching motion to zoom a map or drawing a letter to go to entries that start with that letter in an address book. The gestures that are usually present are tap and double-tap (cousins to the mouse click and double-click), possibly a long press, and some sort of swipe or flicking motion. Some of the mobile operating systems contain more or offer the ability to create new ones.

Deciding Between an Application and a Website

Launching your game as a website offers the following advantages over launching it as an application:

• Speed in development

• Portability

• Ease in deployment

A game that launches as a website has one hub of activity. Although some developers might test the game play on multiple devices, the website itself is treated as the main client for development and testing. Testing primarily in one place will greatly streamline development cycles to push new features or bug fixes. Having the game live on a website also simplifies the deployment strategy. There is one and only one place to push changes and fixes and to monitor for bugs. If you stay within the lowest common denominator of features between HTML5-compliant browsers, possibly with the help of a mobile framework, you could get a product that works reasonably well without the need for much testing.

Although all three major mobile platforms use some form or another of Webkit, they each have their own little quirks. These little nits might cause some unexpected behavior on these browsers. For example, Android devices running 2.2 or higher and newer WebOS phones could use Flash for audio, but Flash is stricken from iOS devices. In this case, using Flash audio on the website would break the experience on some devices.

To counteract these issues, we could deploy our games as applications for each individual platform. Deploying as individual products gives us the opportunity to do the following:

• Tailor the experience to each platform

• Market the applications better

Inversely, deploying for each platform individually increases the development costs both in maintenance of multiple apps and in finding developers who are mobile platform generalists. Later in this chapter, we will discuss in more detail some specific libraries that can help in packaging applications, but first let’s talk generally about what is going on behind the scenes. Whether your game is launched as a website or a mobile application, the one point of commonality is your game assets: the HTML, JS, CSS, and whatever other assets you have created. The difference is in how they will be run. In a mobile application, the files are bundled and run locally. The application is, in its most basic implementation, just a widget of some sort to show HTML content with a little Java, Objective-C, or other native code to bind it all together. Frameworks that might interpret gestures sit at the outermost layer closest to the user. Figure 10-1 shows the breakdown of the individual layers in an Android application.

Figure 10-1. Android application layers

Image

Native code is where we could define new gestures that only a specific operating system might support. In addition to OS-specific gestures, we might expose other features that are accessible only from native code, such as camera or accelerometer support. The biggest advantage to releasing your games as applications is better marketing opportunities. Most mobile platforms have app stores that feature apps that can run on their devices. Some, such as the iPhone App Store and the upcoming Amazon Android App Store, are curated environments, where each app is vetted to make sure it runs properly and as expected. Other stores, such as Android Market, allow the developer to deploy an app and have it almost instantly be available for download or purchase. If your game isn’t packaged as an app, there is no way it can be a featured download in any of the stores. It can also be more difficult to get potential users to buy your game. If you use a website, you would have to set up payment systems as well as handle refunds and download errors. Releasing the app through a store moves that heavy lifting to someone else.

Making your game an application doesn’t come without risks. Apps are vulnerable. They can be copied, cracked, and decompiled. If you make a good game, it may very well get pirated. All that being said, the opportunity for greater exposure, in my humble opinion, far outweighs the risks.

Storing Data on Mobile Devices

Most nontrivial applications have a need to store structured data. The general consensus for mobile devices has been to employ SQLite. In Chapter 1, “Introducing HTML5,” we briefly discussed WebSQL, which is closely linked to SQLite. Note that mobile applications, for the most part, use the SQLite support built into the operating system rather than that of the browser. WebSQL (SQL in the browser) has been deprecated in favor of the NoSQL-like IndexedDB standard.

The application frameworks we will discuss later in this chapter—Appcelerator Titanium and PhoneGap—both allow you to make native OS database calls from your HTML5 applications. If you make extensive use of the database, it won’t be optimal to use one method for the browser and another for mobile applications. Generally, the less code that has to change, the better. Enter Lawnchair.

Relaxing in Your Lawnchair: An Easier Way to Store Data

Lawnchair is a storage API created by some of the same folks behind PhoneGap. It allows us to use a single API to persist data in many backing data stores. We could use Lawnchair for something as simple as save states or as complex as game maps. It gives us a way to future-proof our code. Lawnchair supports the following backends:

• DOMStorage (localStorage)

• WebSQL (both Webkit and Gears)

• Window-Name

• BlackBerry

• IE User data

• IndexedDB

If you are familiar with NoSQL key/value stores such as MongoDB and CouchDB, you will feel right at home with Lawnchair. (Key/value store databases store their data in collections of objects that are maps of properties, generally as a JSON object.) You can create a database and just start populating things in it. You don’t have to declare in advance what properties your objects will have. They can evolve naturally over time. As a result, all objects of the same “type” might not have the same set of properties. The install instructions can be found at http://westcoastlogic.com/lawnchair/. We need to include the Lawnchair.js file and one of the included adaptors.

Getting Started with Lawnchair

The first thing we need to do is create a Lawnchair store.  You can think of it as a bag of objects that are generally alike. You can have as many stores as you want, up to the non-administrator limits of your browser (generally about 5MB, before the user is prompted for permission). Listing 10-1 shows the code to create a classes store and populate it with a couple objects using the save function. Alternatively, we could supply a function to be executed when the save operation is completed.

Listing 10-1. Creating a Lawnchair Store


var classes = new Lawnchair({name:'classes'}, function() {
    this.save({name:'Calculus 101', professor:'Jenkins'});
    this.save({name:'Physics 220', maxClassSize:30});
    this.save({name:'Advanced Physics', prerequisite:'Physics 220'});
});


Lawnchair supplies several functions to retrieve records: each, get, and all. Like its name implies, each iterates over each record in the store and runs a supplied function on the results.  Listing 10-2 shows the code to print out all the names of our classes.

Listing 10-2. Lawnchair each Example


classes.each(function(record) {
   console.log(record.name);
});


get allows us to retrieve a record for a given key and, if found, run a function on the results. Until now, we haven’t talked much about keys. If we don’t specify one when we create our records, Lawnchair generates a GUID string to use as the key for us. Listing 10-3 shows the code to save some records with a custom key and a get function to find them.

Listing 10-3. Lawnchair save and get Examples


classes.save({key:"CISC650", name:"Intro to Computer Science"});
classes.save({key:"CISC615", name:"Analysis of Algorithms"});
classes.get("CISC615",
   function(r){console.log(r);}
);


Up until now, we haven’t talked about removing records. r Lawnchair lets us remove a single record with remove or blow away the whole store with nuke. Listing remove, like get, takes the key of the object to remove. nuke, by default, doesn’t take any parameters, but you can optionally include a callback function to be executed when the nuke is complete. Listing 10-4 shows both methods in action.

Listing 10-4. Lawnchair remove and nuke Examples


classes.remove("CISC615",
   function(r) {console.log("remove completed)}
);
classes.nuke();


Client-Side Scripting Simplified with JQuery and Zepto

Browser-based applications more and more are moving away from a list of static pages and toward one-page applications where interactivity is improved and portions are loaded dynamically. Although many options are available, we will be focusing on JQuery variants and Zepto. These were chosen based on the ubiquity of JQuery as a client-side scripting standard. On the lighter side, Zepto provides some touch screen gestures on top of a JQuery-like interface. JQueryMobile and JQTouch provide more of a framework for HTML5 applications. Their default themes look like native iOS apps, whereas you would have to define your own style sheets when using Zepto.

Using JQuery Variants

JQuery is a library for JavaScript that simplifies traversal of HTML documents, selectors, event handling, and AJAX animations. Polls and analysis vary greatly but the consensus is that for sites where the JavaScript library can be detected, between 50% and 78% use JQuery. JQuery’s functionality can be expanded via user-developed plugins. JQuery is often recognized by its use of the $ and $. functions, the latter of which allows a single discrete function to be called, whereas functions of the former type can be chained together. The two generally used JQuery frameworks/plugins for optimizing a web application are JQueryMobile and JQTouch.

JQueryMobile  (http://jquerymobile.com/) is a framework that focuses on providing a high-grade experience on today’s mobile browsers. It is hosted on the JQuery website, and in theory, the advances made in JQuery will flow into JQueryMobile very quickly. The project attempts to gracefully degrade when displayed in a browser that doesn’t provide full HTML5-compliant capabilities.

JQueryMobile supports many of the gestures that are supported in native mobile applications. In addition to sensing when you change the direction you are holding the device via the orientationchange event, JQueryMobile supports the following touch events:

tap

taphold

swipe

swipeLeft

swipeRight

Earlier in this chapter, we discussed tap. A swipe event is fired when there is contact with the screen and movement of 30 pixels or more up or down (for a general swipe event) or left or right for swipeLeft or swipeRight, respectively.

JQueryMobile includes several CSS transitions for moving between pages. The following transitions are supported:

slide

slideup

slidedown

pop

fade

flip

We could a pop transition to an anchor tag by including the following code:

<a href="EB9780132685108_20.html" data-transition="pop">I'll pop</a>

Inversely, including data-back="true" will reverse the transition when the Back button is hit.

In addition to the smooth CSS transitions, JQueryMobile’s components can be themed. It has a built-in theme that closely mimics the user interface of iOS applications. At present, there isn’t a theme to make apps look more “Android like” (or for any other non-iOS platform). You could probably attribute this to the evolution of native apps on both platforms. Native applications from outside developers on iOS didn’t arrive for nearly a year from the device launch. The advice from Apple at the time was to make web apps. Android, on the other hand, supported a software development toolkit from day one.

JQTouch (http://jqtouch.com/) shares a lot of ground with JQueryMobile. JQTouch focuses on smaller device screens, whereas JQueryMobile attempts to be device independent. Like JQueryMobile, JQTouch built-in themes support iOS devices and not much else. The number of built-in touch events is somewhat limited compared to JQueryMobile. Only tap and swipe are predefined. You can, however, build more gestures into your application by interpreting the return values from touchmove.

Using Zepto.js

Last but not least is Zepto.js (http://zeptojs.com/). It is not officially a JQuery variant but it does have a JQuery-compatible chaining syntax. It is also incredibly small. The library is under 5KB after being minified and gzipped. This comes at the expense of not including styling for components as JQTouch and JQueryMobile do. In addition to JQuery selectors and chaining, Zepto supports JQuery-style HTTP GET, POST, and AJAX calls and can sense the mobile operating system on which it is running. Touch event support is fairly robust with listeners for tap, doubleTap, swipe, swipeLeft, and swipeRight.

Architecting Your Applications with JoApp

Jo (http://joapp.com/) is a cross-platform JavaScript framework for HTML5 apps. The same code can be used to deploy an application in Safari, Chrome, Firefox, iOS, Android, and WebOS. Jo uses CSS3 as much as possible to handle presentation and animation. Jo also provides encapsulation for persistent storage and is able to unobtrusively work with other JavaScript libraries. Jo concerns itself with the visual elements of an application, leaving the device-specific minutiae to the enclosing framework—for example, Phone-Gap and Titanium, which we will discuss later in this chapter. Like the aforementioned JQTouch and JqueryMobile, Jo provides a fairly attractive iOS theme. Listing 10-5 shows the HTML for a basic Jo application. No other content is needed if the application creates all user interfaces in code.

Listing 10-5. Basic Jo Application


<html>
<head>
   <link rel="stylesheet" type="text/css" href="css/aluminum.css">
   <link rel="stylesheet" type="text/css" href="css/webkit.css">
   <!-- <link rel="stylesheet" type="text/css" href="css/webos.css"> -->
   <!-- <link rel="stylesheet" type="text/css" href="css/chrome.css"> -->
</head>
<body>

<!-- any static page content goes here -->

<!-- load jo library -->
<script src="jo_min.js"></script>

<!-- any application JavaScript files go here -->
<script src="hello.js"></script>

</body>
</html>


Jo includes a set of skinned components and controls to create user interfaces. These can be created using JavaScript or by using HTML. By default, HTML will ignore tags it doesn’t recognize, so Jo can coexist with regular HTML code. Listing 10-6 shows the code to create a screen and embed a Canvas inside it.

Listing 10-6. Displaying a Canvas in Jo


//initialize jo
jo.load();

//define a wrapper for document.body
var scn = new joScreen();

var canvas = new joHTML("<canvas height="200" width="200"></canvas>");
scn.push(canvas);


Jo provides an easy means to meld together game content and the application using containers. Jo’s interfaces use a stack architecture that’s not unlike a deck of cards, allowing you to discretely separate screens.

Choosing an Application Framework

We have many options for creating applications using HTML and deploying them to mobile devices. The two frameworks we will discuss in this section—PhoneGap and Appcelerator Titanium—expose native mobile device functionality to JavaScript. Later in this section, we will package the same application with both of them targeting Android. The application we’ll be developing uses Zepto.js to capture touch gestures and for determining the operating system. The app draws an HTML file that displays the OS and viewable window dimensions and also has a Canvas that responds to touch events.

PhoneGap

PhoneGap (http://phonegap.com) is a mobile application development framework created by Nitobi Software. The framework allows access to native components of mobile devices such as the accelerometer, camera, contacts, and the file system via a JavaScript interface. All application code is written using JavaScript and HTML and is bound at compile time to the corresponding Java or iOS APIs. Experienced developers could additionally expose other native APIs to the JavaScript interface. Currently, the framework supports developing applications using the following operating systems with varying levels of support for HTML5:

• iOS

• Android

• WebOS

• Blackberry

• Windows Mobile

• Symbian

Diving into the PhoneGap APIs

PhoneGap contains about a dozen APIs, listed next, for making applications. Virtually anything that can be done in a native app has a PhoneGap API:

• Accelerometer

• Camera

• Capture

• Compass

• Connection

• Contacts

• Device

• Events

• File

• Geolocation

• Media

• Network

• Notification

• Storage

Of the aforementioned APIs, the most important is the Events API. When an application loads, by virtue of the way HTML and JavaScript work, it is possible to call functions on objects before they are fully initialized. The Events API exposes an event called deviceready that fires when phonegap.js is ready to start receiving commands. Every PhoneGap application should subscribe to deviceready. Listing 10-7 shows a simple example of the code we would need to listen for the event.

Listing 10-7. Listening for the deviceready Event


document.addEventListener("deviceready", doStuff, false);

function doStuff() {
   // Now safe to use the PhoneGap API
}


In traditional browsers, JavaScript has no access to the local file system, thus handing that heavy lifting to code executing on the server side. This is a pretty hefty restriction for an application that doesn’t have a server. Luckily for us, PhoneGap does give us a way to read, write, and upload files from JavaScript code. The FileReader  object permits us to read files from the file system. The object only has three functions: readAsText takes a filename as a parameter and stores that text content of the file in the result property on the FileReader object. readAsDataURL returns the specified file as a base64-encoded URI string. For a refresher on how data URI strings operate, look at the section on images in Chapter 5, “Creating Games with the Canvas Tag.” The abort function quits reading the file. In addition to the result property, there is also an error property to store any errors, a readyState property to initiate the status of the load in progress, as well as events that can be subscribed to for updates on progress and status.

The FileWriter object,  like FileReader, contains properties for the readyState and errors. In addition to the expected write and abort functions, you can also seek to a position in a file and truncate it to the length of a specified number of bytes. Listing 10-8 shows the code to write a string to a file (test.txt) and truncate it to a length of 10 bytes.

Listing 10-8. PhoneGap FileWriter Example


var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "test.txt");
writer.write("writing some text");
writer.truncate(10);


Lastly, the FileUpload object gives us a way to upload files to a server using HTTP POST. It has a sole-function upload that takes as parameters the file to upload, the URL to POST to, callbacks for success and failure, and an options object to pass additional information with the request.

The isReachable function on the Network object allows us to check for connectivity given a URL to connect to and a callback to execute when connectivity is determined. We can use the results to determine whether we are offline, connected to the carrier’s network, or connected to Wi-Fi.

PhoneGap is capable of getting the user’s attention with several different audio, visual, and sensory notifications. In addition to a stylized alert message that we would see in any browser, we can vibrate the phone for a number of milliseconds, make a beep sound a number of times, or show a confirmation dialog.

For further documentation, you can visit http://docs.phonegap.com.

Appcelerator Titanium

Appcelerator Titanium (www.appcelerator.com) is a software development toolkit that allows developers to create desktop and mobile application using web technologies such as HTML, JavaScript, and CSS. On the desktop, the experience is reminiscent of and is often compared to the Adobe AIR runtime.

For mobile devices, Titanium only supports Android and iOS. Although that is not technically cross-platform, iOS and Android account for most of the smart phones being sold. The reduced focus to cutting-edge mobile operating systems allows the creators to really refine the experience on iOS and Android.

Diving into the Appcelerator Titanium APIs

Whereas PhoneGap expects you to use HTML and CSS or another library altogether for laying out user interfaces, Appcelerator Titanium has its own set of JavaScript APIs to create UI elements. These elements produce native components during compilation and keep the secret that your app was built with Titanium. You are also free to develop your application using just HTML, JS, and CSS.

Titanium.Filesystem, and the object File it exposes, allows you to interact with the file system. Any operation that you would expect from a traditional compiled language—such as creating and reading files and directories, creating temporary files, and setting flags on them—is supported in this module. This is the only area where Titanium differs from PhoneGap. Having to only deal with Android and iOS, which are fairly feature rich, makes it easier to enable this functionality.

Titanium’s Network module is equally robust. Like the PhoneGap counterpart, it can detect network connectivity and determine whether the host is connected via Wi-Fi or cellular service. The module can create and receive HTTP and TCP requests and search for connected Bonjour/Zeroconf services. Bonjour is the name of Apple’s implementation of Zeroconf, which allows computers, servers, and peripherals such as printers and scanners to connect with little configuration from the user.

Packaging Android Applications with Titanium and PhoneGap

Now that we have talked about Titanium and PhoneGap, let’s dig into them a little bit more by packaging an application with them. The application is fairly basic in nature, displaying some information about the mobile browser and responding to some events. To assist us with mobile gestures, we will be using Zepto.js. The core HTML file we will be using is shown in Listing 10-9. It uses window.innerHeight/innerWidth to retrieve the height and width of the browser window and properties on the $.os object to show the operation system and version

Listing 10-9. HTML File for Mobile App


<!DOCTYPE HTML>
<html>
        <head>
                <script src="zepto.min.js"></script>
                <title>Test Application</title>
        </head>
        <body>
       <div id="t"></div>
                <canvas id="canvas" height="200" width="200"
            tabindex="1">
                </canvas>
                <div id="os"></div>
                <div id="browserWidth"></div>
                <div id="browserHeight"></div>

       <script>
           function determineOS() {
             if ($.os.ios == true || $.os.iphone == true || $.os.ipad == true ) {
               return "iOS/iPhone/iPad " + $.os.version;
             } else if ($.os.android == true) {
               return "Android "+ $.os.version
             } else {
               return navigator.userAgent;
             }
           }

           $("#os").text("Operating System:"+ determineOS());
           $("#browserHeight").text("Height: "+window.innerHeight + "px" + " ");
           $("#browserWidth").text("Width: "+window.innerWidth);

           $('#canvas').bind('click', function(event){ $("#t").text('tapped at '+new Date()) });
                        $("#canvas").bind('tap', function(evt) {
               $("#t").text('tapped at '+new Date());
                        });
                </script>
        </body>
</html>



Sound on Android Devices

Although there is far better support than usual for the audio element, some Webkit browsers, such as the one in Android 2.2, don’t natively support it. A workaround for this lack of support is to use a video element with the audio file as the source and then call play(). If you’re using a framework such as PhoneGap or Titanium, this won’t be a problem, but it is something to be aware of if you are rolling your own solution.


Packaging an Application with Titanium

Creating a project with Titanium is simple, requiring only a few filled-in text boxes and a few button clicks. Figure 10-2 shows the New Project screen for a sample Titanium application.

Figure 10-2. Creating a new project in Titanium

Image

From the Titanium application, we can run our apps in the Android or iOS emulator, on physical devices, or deploy them to their respective app stores, as shown in Figure 10-3.

Figure 10-3. Running an emulator in Titanium

Image

Figure 10-4 shows a list of the files for our application. Of particular note to us is the Resources directory (which houses all our application code) and tiapp.xml (which describes how our app will behave on iOS and Android).

Titanium maintains its own Android images just for Titanium. Any modifications won’t be persisted, as Titanium regenerates them from time to time. Behind the scenes, when you deploy to the emulator, Titanium launches the selected image and compiles and deploys the application.

Figure 10-4. Application directory structure in Titanium

Image

Titanium uses a file named app.js to describe the user interface and logic of your application. Listing 10-10 shows the code to use Titanium’s JavaScript API to create a window, populate it with a WebView, and show it to the user.

Listing 10-10. Sample Application app.js File


// this sets the background color of the master UIView
//(when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000'),

//
// create root window
//
var win1 = Titanium.UI.createWindow({
    title:'App',
    backgroundColor:'#fff'
});

var webview = Titanium.UI.createWebView({
    url:'index.html'
});

win1.add(webview);

// open window
win1.open();


After we place our index.html and zepto.min.js files in the same directory as app.js, we are ready to run our application.

Packaging an Application with PhoneGap

Instead of using a customized emulator launcher like Titanium does, PhoneGap relies strongly on the existing Android tool chain. This means that you can use the Android plugin with the Eclipse IDE like a native application would. Components of the AndroidManifest.xml configuration file that are automagically created for you in Titanium have to be coded by hand with PhoneGap. For the purposes of this example, we assume you have the Android plugin installed in your IDE of choice.

Creating a project is pretty straightforward and bears no hallmarks that are different from creating a native application. Figures 10-5 and 10-6 show the creation screens for our project. In Figure 10-6, we left the option “Create ‘Hello World!’ project” selected because that reduces the amount of Java code we will have to write.

PhoneGap exposes Java functionality to HTML applications using two files: a Java library named phonegap.jar and its JavaScript counterpart, phonegap.js. phonegap.jar needs to be placed somewhere on the application path. We will leave phonegap.js for a bit later.

Figure 10-5. Creating an application using PhoneGap

Image

Figure 10-6. Creating an application using PhoneGap (continued)

Image

Listing 10-11 shows the additions we must add to AndroidManifest.xml to allow PhoneGap to do its work. The snippet begins with a tag telling Android what types of screens this application is allowed to operate on. Next is a series of enabled permissions for components of the device, such as camera access, contacts, audio, and GPS. In Android, every application must explicitly declare which permissions it will use. For our sample application, the sole permission we use is android.permission.INTERNET, but Listing 10-11 shows the required permissions to enable all features of PhoneGap.

Listing 10-11. Additions to AndroidManifest.xml


<supports-screens android:largeScreens="true"
android:normalScreens="true" android:smallScreens="true"
android:resizeable="true" android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<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" />


To the application tag in the AndroidManifest.xml file, we also need to add the following:

android:configChanges="orientation|keyboardHidden"

This tells Android that when the specified changes happen (in this case, the user rotating the device and sliding in/out the keyboard), this application will handle it and not to execute the default behavior and relaunch the application.

Next, we need to make some changes to the sample Activity file Android has created for us. Activities represent a single screen display. Unless you have a really good reason to or would like to tweak Java code, you can get along with solely the changes shown in Listing 10-12.

Listing 10-12. Sample Application Activity File


package com.html5book;

import android.app.Activity;
import android.os.Bundle;
import com.phonegap.*;

public class App extends DroidGap {
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                super.loadUrl("file:///android_asset/www/index.html");
      }
}


Just as we only had to concern ourselves with the Resources directory in Titanium, after initial setup, there is just one primary directory in which we will be working on PhoneGap. We even saw a hint of this when modifying the Java file. We need to create a directory and subdirectory on our path named assets and assets/www, respectively. This is where all our HTML-related application files will live. android_asset is a link to assets. To expose our Java functionality to the application, we just need to copy the phonegap.js file to assets/www. Figure 10-7 shows the application directory layout for our application.

Figure 10-7. Application directory structure in PhoneGap

Image

As opposed to needing a special application to build, launch, or install our application, we can use our favorite IDE or work directly from the command line using the build.xml file.

Summary

In this chapter, we discussed various libraries and frameworks to create HTML5 applications on mobile devices. We focused on libraries that expose touch events and storage options. We looked in detail at two frameworks to package applications: PhoneGap and Appcelerator Titanium. Finally, we used those frameworks to package some applications.

Exercises

1. What is a workaround for playing audio using HTML5 in Android 2.2 browsers?

2. What are the pros and cons of using Appcelerator Titanium versus PhoneGap?

3. What is an advantage of using Lawnchair or any other NoSQL-inspired storage solution over a SQLite database?

4. Which operating system is currently a no-go if you want to create HTML5 applications?

You can download chapter code and answers to the chapter exercises at www.informit.com/title/9780321767363.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.61.226