Chapter 45

HTML5

Prior to the current wave of interest in mobile applications, the technology du jour was web applications. A lot of attention was paid to AJAX, Ruby on Rails, and other techniques and technologies that made the experience of using web applications close to, and sometimes even superior to, the experience of using a desktop application.

The explosion of web applications eventually drove the next round of enhancements to web standards, collectively called HTML5. Android 2.0 was the first version to add support for these HTML5 enhancements. Notably, Android supports offline applications and Web Storage, meaning that HTML5 becomes a relevant technique for creating Android applications, without dealing with Java.

Offline Applications

The linchpin for using HTML5 for offline applications—on Android or elsewhere—is that those applications can be used when there is no Internet connectivity, either on the client side (e.g., on an airplane sans Wi-Fi) or on the server side (e.g., due to web server maintenance).

What Does It Mean?

Historically, web applications have had this annoying tendency to require web servers. This led to all sorts of workarounds for offline use, up to and including shipping a web server and deploying it to the desktop.

HTML5 solves this problem by allowing web pages to specify their own caching rules. A web app can publish a cache manifest, describing which resources

  • Can be safely cached, such that if the web server is unavailable, the browser can use the cached copy.
  • Cannot be safely cached, such that if the web server is unavailable, the browser should fail as it normally would.
  • Have a “fallback” resource, such that if the web server is unavailable, the cached fallback resource should be used instead.

For mobile devices, this means that a fully HTML5-capable browser should be able to load all its assets up front and keep them cached. If the user loses connectivity, the application will still run. In this respect, the web app behaves almost identically to a regular app.

How Do You Use It?

For this chapter, we will use the Checklist “mini app” created by Alex Gibson. While the most up-to-date version of this app can be found at the MiniApps web site (http://miniapps.co.uk/), this chapter will review the HTML5/Checklist copy found in the Source Code/Download area of the Apress web site (www.apress.com). This copy is also hosted online on the CommonsWare site, and you can easily locate it directly via the shortened URL http://bit.ly/cw-html5.

About the Sample App

Checklist is, as the name suggests, a simple checklist application. When you first launch it, the list will be empty, as shown in Figure 45–1.

images

Figure 45–1. The Checklist app, as initially launched

You can enter some text in the top field and click the Add button to add it to the list, as shown in Figure 45–2.

images

Figure 45–2. The Checklist, with one item added

You can “check off” individual items, which are then displayed in strikethrough, as shown in Figure 45–3.

images

Figure 45–3. The Checklist, with one item marked as completed

You can also delete the checked entries (via the Delete Checked button) or all entries (via the Delete All button), which will pop up a confirmation dialog box before proceeding, as shown in Figure 45–4.

images

Figure 45–4. The Checklist's delete confirmation dialog box

“Installing” Checklist on Your Android Device

To access Checklist on your Android device, visit the hosted edition at http://bit.ly/cw-html5. You can then add a bookmark for it (choose More images Add bookmark in the browser's options menu) to come back to it later.

You can even set up a shortcut for the bookmark on your home screen, if you so choose—just long-tap the background, choose Bookmark, and then choose the Checklist bookmark you set up before.

Examining the HTML

All the functionality in the Checklist app is accomplished using just a handful of lines of HTML:

<!DOCTYPE html>
<html lang="en" manifest="checklist.manifest">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Checklist</title>
<meta name="viewport"
  content="width=device-width; initial-scale=1.0; maximum-scale=1.0;images
 user-scalable=0;" />
<meta name="apple-mobile-web-app-capable" content="yes" />

<meta name="apple-mobile-web-app-status-bar-style" />
<link rel="apple-touch-startup-image" href="splashscreen.png" />
<link rel="stylesheet" href="styles.css" />
<link rel="apple-touch-icon-precomposed"
      href="apple-touch-icon-precomposed.png" />
</head>
<body>
<section>
 <header>
 <button type="button" id="sendmail">Mail</button>
 <h1>Checklist</h1>
 </header>
 <article>
    <form id="inputarea" onsubmit="addNewItem()">
    <input type="text" name="name" id="name" maxlength="75"
                  autocorrect placeholder="Tap to enter a new item&hellip;" />
    <button type="button" id="add">Add</button>
  </form>
  <ul id="maillist">
    <li class="empty"><a href="" id="maillink">Mail remaining items</a></li>
  </ul>
  <p id="totals"><span id="tally1">Total: <span id="total">0</span></span>
        <span id="tally2">Remaining: <span id="remaining">0</span></span></p>
  <ul id="checklist">
    <li class="empty">Loading&hellip;</li>
  </ul>
 </article>
 <fieldset>
  <button type="button" id="deletechecked">Delete Checked</button>
  <button type="button" id="deleteall">Delete All</button>
 </fieldset>
</section>
<script src="main.js"></script>
</body>
</html>

For the purposes of offline applications, though, the key is the manifest attribute of our html element:

<html lang="en" manifest="checklist.manifest">

Here, we specify the relative path to a manifest file, indicating what the rules are for caching various portions of this application offline.

Examining the Manifest

Because the manifest is where all the fun is, let's look at Checklist's manifest:

CACHE MANIFEST
#version 54
styles.css
main.js
splashscreen.png

The HTML5 manifest format is extremely simple. It starts with a CACHE MANIFEST line, followed by a list of files (technically, relative URLs) that should be cached. It also supports comments, which are lines beginning with #.

The manifest can also have a NETWORK: line, followed by relative URLs that should never be cached. Similarly, the manifest can have a FALLBACK: line, followed by pairs of relative URLs: the URL to try to fetch off the network, followed by the URL of a cached resource to use if the network is not available.

In principle, the manifest should request caching for everything that the application needs to run, though the page that requested the caching (index.html in this case) is also cached.

Web Storage

Caching the HTML5 application's assets for offline use is all well and good, but that will be rather limiting on its own. In an offline situation, the application would not be able to use AJAX techniques to interact with a web service. So, if the application is going to be able to store information, it will need to do so on the browser itself.

Everything from cookies through to Google Gears has been used to grapple with this problem, with the latter tool blazing the trail for what is now variously called Web Storage or DOM Storage for HTML5 applications. An HTML5 app can store data persistently on the client, within client-imposed limits. That, in conjunction with offline asset caching, means an HTML5 application can deliver far more value when it lacks an Internet connection, or for data that just does not make sense to store “in the cloud.”

NOTE: Technically, Web Storage is not part of HTML5, but rather is a related specification. However, it tends to get lumped in with HTML5 in common conversation.

What Does It Mean?

On a Web Storage–enabled browser, your JavaScript code will have access to a localStorage object, representing your application's data. More accurately, each origin (i.e., domain) will have a distinct localStorage object on the browser.

The localStorage object is an associative array, meaning you can work with it via either numerical indexes or string-based keys. Values typically are strings. You can do the following with localStorage:

  • Find out how many entries are in the array via length()
  • Get and set items by key via getItem() and setItem()
  • Get the key for a numerical index via key()
  • Remove individual entries via removeItem() or remove all items via clear()

This means you do not have the full richness of a SQL database, like you might have with SQLite in a native Android application. But, for many applications, this should suffice.

How Do You Use It?

Checklist stores the list items as keys in the associative array, with a value of 0 for a regular item and 1 for a deleted item. Here, we see the code for putting a new item into the checklist:

try {
  localStorage.setItem(strippedString, data);
}
catch (e) {
  if (e == QUOTA_EXCEEDED_ERR) {
    alert('Quota exceeded!'),
  }
}

Following is the code where those items are pulled back out of storage and put into an array for sorting and, later, display as DOM elements on the web page itself:

/*get all items from localStorage and push them one by one into an array.*/
for (i = 0; i <= listlength; i++) {

  var item = localStorage.key(i);
  myArray.push(item);
}

/*sort the array into alphabetical order.*/
myArray.sort();

When the user checks the check box next to an item, the storage is updated to toggle the checked setting persistently:

/*toggle the check flag.*/
if (target.previousSibling.checked) {
  data = 0;
}
else {
  data = 1;
}
/*save item in localStorage.*/
try {
  localStorage.setItem(name, data);
} catch (e) {

  if (e == QUOTA_EXCEEDED_ERR) {
    alert('Quota exceeded!'),
  }
}

Checklist also has code to delete items from storage, either all items marked as checked or all items. Following is the code to delete all checked items:

/*remove every item from localStorage that has the data flag checked.*/
while (i <= localStorage.length-1) {

  var key = localStorage.key(i);
  if (localStorage.getItem(key) === '1') {
    localStorage.removeItem(key);
  }
  else { i++; }
}

And here is the code to delete all items:

/*deletes all items in the list.*/
deleteAll: function() {

  /*ask for user confirmation.*/
  var answer = confirm("Delete all items?");

  /*if yes.*/
  if (answer) {

    /*remove all items from localStorage.*/
    localStorage.clear();
    /*update view.*/
    checklistApp.getAllItems();
 }
 /*clear up.*/
 delete checklistApp.deleteAll;
},

Web SQL Database

Android's built-in browser also supports a Web SQL Database option, which enables you to use SQLite-style databases from JavaScript. This adds a lot more power than basic Web Storage provides, albeit at a complexity cost. It is also not part of an active standard—the Web Hypertext Application Technology Working Group (WHATWG) team working on this standard has set it aside for the time being.

You might consider evaluating Lawnchair, which is a JavaScript API that allows you to store arbitrary JavaScript Object Notation (JSON)-encoded objects. It will use whatever storage options are available, and therefore will help you deal with cross-platform variety.

Going to Production

Creating a little test application requires nothing magical. Presumably, though, you are interested in having other people use your application—perhaps many others. Classic Java-based Android applications have to deal with testing, having the application digitally signed for production, distributing it through various channels (such as the Android Market), and providing updates to the application by one means or another. Those issues do not all magically vanish because HTML5 is used as the application environment. However, HTML5 does change things significantly from what Java developers have to do.

Testing

Since HTML5 works in other browsers, testing your business logic could easily take advantage of any number of HTML and JavaScript testing tools, from Selenium to QUnit to Jasmine.

For testing on Android proper—to ensure there are no issues related to Android's browser implementation—you can use Selenium's Android Driver or Remote Control modes.

Signing and Distribution

Unlike native Android applications, you do not need to worry about signing your HTML5 applications. The downside of this is that there is no support for distribution of HTML5 applications through the Android Market, which today supports only native Android apps. Users will have to find your application by one means or another, visit it in the browser, bookmark the page, and possibly create a home screen shortcut to that bookmark.

Updates

Unlike native Android applications, which by default must be updated manually, HTML5 applications will be transparently updated the next time the user runs the app while connected to the Internet. The offline caching protocol will check the web server for new editions of files before falling back to the cached copies. Hence, there is nothing more for you to do other than publish the latest web app assets.

Issues You May Encounter

Unfortunately, nothing is perfect. While HTML5 may make many things easier, it is not a panacea for all Android development problems.

This section covers some potential areas of concern you will want to consider as you move forward with HTML5 applications for Android.

Android Device Versions

Not all Android devices support HTML5—only those running Android 2.x or higher. Ideally, therefore, you should do a bit of user-agent sniffing on your web server and redirect older Android users to some other page explaining the limitations in their device.

Here is the user-agent string for a Google/HTC Nexus One device running Android 2.1:

Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; Nexus One Build/ERE27)images
 AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17

As you can see, it is formatted like a typical modern user-agent string, meaning it is quite a mess. It does indicate it is running Android 2.1-update1.

Eventually, somebody will create a database of user-agent strings for different device models, and from there we can derive appropriate regular expressions or similar algorithms to determine whether a given device can support HTML5 applications.

Screen Sizes and Densities

HTML5 applications can be run on a wide range of screen sizes, from QVGA Android devices to 1080p LCDs and beyond. Similarly, screen densities may vary quite a bit, so while a 48×48-pixel image on a smartphone may be an appropriate size, it may be too big for a 1080p television, let alone a 24-inch LCD desktop monitor.

Other than increasing the possible options on the low end of screen sizes, none of this is unique to Android. You will need to determine how best to design your HTML and CSS to work on a range of sizes and densities, even if Android were not part of the picture.

Limited Platform Integration

HTML5, while offering more platform integration than ever before, does not come close to covering everything an Android application might want to be able to do. For example, an ordinary HTML5 application cannot do the following:

  • Launch another application
  • Work with the contacts database
  • Raise a notification with the stock browser (note that Firefox for Android has a solution for this)
  • Do work truly in the background (though web workers may alleviate this somewhat someday)
  • Interact with Bluetooth devices
  • Record audio or video
  • Use the standard Android preference system
  • Use speech recognition or text-to-speech

Many applications will not need these capabilities, of course. And other application environments, like PhoneGap (covered in Chapter 46), will likely evolve into “HTML5 Plus” for Android. That way, you could create a stock application that works across all devices and a separate enhanced Android application that leverages greater platform integration, at the cost of some additional amount of programming.

Performance and Battery

There has been a nagging concern for some time that HTML-based user interfaces are inefficient compared to native Android UIs, in terms of processor time, memory, and battery. For example, one of the stated reasons for avoiding BONDI-style web widgets for the Android home screen is the performance impact.

Certainly, it is possible to design HTML5 applications that will suck down the battery. For example, if you have a hunk of JavaScript code running every second indefinitely, that is going to consume a fair amount of processor time. However, outside of that, it seems unlikely that an ordinary application would be used so heavily as to materially impact battery life. Certainly, more testing will need to be done in this area.

Also, an HTML5 application may start up a bit slower than other applications, particularly if the browser has not been used in a while or if the network connection is there but has minimal bandwidth to your server.

Look and Feel

HTML5 applications can certainly look very slick and professional—after all, they are built with web technologies, and web apps can look very slick and professional.

However, HTML5 applications will not necessarily look like standard Android applications, at least not initially. Some enterprising developers will, no doubt, create some reusable CSS, JavaScript, and images that will, for example, mirror an Android native Spinner widget (a type of drop-down control). Similarly, HTML5 applications will tend to lack options menus, notifications, or other UI features that a native Android application may well use.

This is not necessarily bad. Considering the difficulty in creating a very slick-looking Android application, HTML5 applications may tend to look better than their Android counterparts. After all, there are many more people skilled in creating slick web apps than there are people skilled in creating slick Android apps.

However, some users may complain about the look-and-feel disparity, just because it is different.

Distribution

HTML5 applications can be trivially added to a user's device—browse, bookmark, and add a shortcut to the home screen. However, HTML5 applications will not show up in the Android Market, so users trained to look at the Market for available applications will not find HTML5 applications, even ones that may be better than their native counterparts.

It is conceivable that, someday, the Android Market will support HTML5 applications. It is also conceivable that, someday, Android users will tend to find their apps by means other than searching the Android Market, and will be able to get their HTML5 apps that way. However, until one of those becomes true, HTML5 applications may be less “discoverable” than their native equivalents.

Browser Changes Post Ice Cream Sandwich

Google has announced that their future direction for the stock Android browser will be Chrome (or a version of Chrome derived for Android). No indication was given with the Android 4.0 release as to whether the change will come through an incremental process slowly converging on a Chrome-like browser, or via a big-bang change in a future release. When the change does occur, some of the nuances of using HTML5, and indeed some of the supported features, are likely to change. This will impact all of your users for any HTML5 apps, barring those using alternative browsers.

HTML5 and Alternative Android Browsers

While the built-in Android browser will be the choice of many Android users, there are other browsers available. Here is how some of the better-known alternatives stand in terms of HTML5 support:

  • Firefox Mobile: Still in beta form after quite some time, supports offline caching and local storage. However, it is unable to run the Checklist sample correctly at this time.
  • Opera Mobile: A steadily improving offering, recently adding features like haptic feedback support. Does not support local storage, rendering Checklist moot. It also does not support offline caching at this time.
  • Dolphin Browser HD 4.0: Supports offline caching and local storage. While there are slight rendering problems—perhaps CSS-related—in Checklist, the application otherwise runs fine, even without an Internet connection.

HTML5: The Baseline

HTML5 is likely to become rather popular for conventional application development. It gives web developers a route to the desktop. It may be the only option for Google's Chrome OS. And, with ever-improving support on popular mobile devices—Android among them—developers will certainly be enticed by another round of “write once, run anywhere” promises.

It is fairly likely that, over time, HTML5 will be the number two option for Android application development, after the conventional Java application written to the Android SDK. That will make HTML5 the baseline for comparing alternative Android development options—not only will those options be compared to using the SDK, they will be compared to using HTML5.

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

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