Lesson 12: Convert Your App to a Native App

Lesson 12: Convert Your App to a Native App

Introduction

The time has come to unleash WatzThis on the world and to become rich and famous! Everyone in the office agrees that right now is the perfect time for an app like WatzThis to revolutionize the way people do the things that WatzThis helps them to do. You have to move fast and get it out there, so people can use it right away!

There's just one thing left to do: figure out how to distribute your app.

Currently, all the major mobile operating systems have their own app stores where users can search for, download, and install apps. App stores serve several important purposes:

  • Provide a central location for users to find and update apps
  • Ensure a level of app quality and security by requiring apps to be tested before the store will list them
  • Simplify the process of accepting payment for apps

WatzThis.com is on the cutting edge of cross-platform HTML5 app technology, however, and the app stores haven't caught up yet. Most app stores—including Apple's App Store and Google Play (formerly known as the Android Market)—don't provide a way for developers to list and sell HTML5 Web apps.

Until app stores start selling Web apps and those apps have the same functionality as native ones, Web app developers can cross over from the Web app world to the native app world by using a bridging framework. To put it simply, a bridging framework converts Web apps into native apps. At the same time, it enables Web apps to access functions of the native device that would otherwise be off-limits.

The most popular bridging framework, and the one we'll talk about in this lesson, is PhoneGap. Other bridging frameworks include:

  • Rhomobile Suite: The Rhomobile Suite uses the Ruby programming language, and it specializes in creating database-intensive mobile applications.
  • Titanium Appcelerator: Titanium allows programmers to create native mobile and desktop applications from Web apps.
PhoneGap Logo Author: Yohei Shimomae

All About PhoneGap

A company called Nitobi, which is now part of Adobe, created PhoneGap. PhoneGap is free and open source, meaning anyone can use it for any purpose (commercial or not). PhoneGap also goes by the name Cordova, which is the official name of the open-source project. It's confusing, I know. But if you just remember that Cordova is PhoneGap, everything will be fine.

PhoneGap takes Web apps written in HTML5, CSS, and JavaScript and wraps them inside a native app. This native wrapper acts like a Web browser in that it reads and displays Web content. But the PhoneGap wrapper is like a mobile Web browser of the future!

Way back in Lesson 7, we talked about the HTML5 Device Access Working Group and the Device Access application programming interfaces that it's writing. I mentioned at that point that only some of these APIs were currently available in mobile browsers. This is still true, but PhoneGap provides the loophole that lets you use these APIs today.

The World Wide Web Consortium (W3C) has created many device APIs to allow Web apps to interact with native device features. Most mobile browsers don't understand these APIs, but the PhoneGap wrapper does. If you use these device APIs in your Web app and then compile your Web app into a native app, you can use native device features such as the compass, accelerometer, camera, contacts, and alert notifications.

Here are a few examples of things you can do through PhoneGap that aren't yet possible using HTML5 and a mobile browser:

  • Create apps that use a device's built-in camera. If some part of your HTML5 mobile app depends on users being able to capture video using the device's camera, the only way to do this is to use the getUserMedia API, which doesn't work in most mobile browsers. PhoneGap supports it, however.
  • Make apps that can access a user's contacts and calendar. Some mobile apps can search the contacts on the user's phone or read and create events in that phone's calendar app. This functionality requires a deeper level of access to native features than a Web browser has.
  • Invent apps that can notify the user of events when the app is closed. Browser-based apps run only when your browser is open. If your app needs to send the user notifications and reminders when the user is using other apps ("It's your move in the game" or "Reminder: you have an important meeting coming up!"), you need to use native features of the phone.

The exciting thing is that PhoneGap lets you access native devices using the same APIs that all mobile Web browsers will eventually support. PhoneGap is just there to provide the "bridge" between current browser technology and the standards that are in development for future browsers. In other words, many of the apps you develop in HTML5 and convert to native apps with PhoneGap today will likely work as pure HTML5 apps in future mobile browsers. Or, the only changes you'll need to make will be as a result of changes to the as-yet-unfinished specifications for these new device APIs.

Here's a list of device APIs that PhoneGap currently supports for iOS and Android:

  • Accelerometer
  • Camera
  • Compass
  • Contacts
  • File
  • Geolocation
  • Media
  • Network
  • Notification (Alert)
  • Notification (Sound)
  • Notification (Vibration)
  • Storage

Cross-Platform Native App Development

The other great thing about bridging frameworks is that you can use the same HTML5, CSS, and JavaScript code to create native apps for many platforms (such as iOS, Android, Windows Mobile, and so forth).

In order to allow you (the Web developer) to write your code once and then deploy it to multiple mobile operating systems, the PhoneGap developers have created a separate PhoneGap wrapper for each mobile phone operating systems. Instead of writing your app multiple times in different programming languages, you can use your same code but wrap it with the appropriate PhoneGap code for each operating system.

PhoneGap enables cross-platform native mobile apps

Thousands of apps that are distributed via the app stores were originally written using HTML5 technologies and then converted into native apps with PhoneGap. Perhaps the highest-profile one, with over a million downloads, is the official Wikipedia app for Android. I'm certain that WatzThis will be even more popular!

How to Write Web Apps for PhoneGap

Web apps that you want to convert into PhoneGap apps must meet one very strict requirement: They must use only client-side code for the user interface. This means you must rewrite any server-side pages as HTML, CSS, and JavaScript files. If you need a refresher on client side versus server side, we covered that back in Lesson 5, Chapter 2.

For example, content management systems such as WordPress or Drupal use server-side templates (written with PHP or another server-side programming language) to dynamically assemble pages on the server before sending them to a Web browser. Since PhoneGap creates self-contained native apps, this sort of server-side code won't work because PhoneGap can't display it in offline mode.

Instead, to use dynamic data in PhoneGap apps, you need to use JavaScript code to retrieve dynamic data from a server or local device storage with AJAX techniques. (Remember AJAX from Lesson 6, Chapter 2? Boy, we're revisiting a lot of information in this lesson.) An example of this method of using dynamic data is the way the WatzThis app gets data from Google Maps to display the user's location.

The important thing to keep in mind is that Web apps must contain only HTML, CSS, and JavaScript (along with included resources like images, videos, and animations, of course) in order for PhoneGap to convert them into native apps successfully.

Building Native Functions into WatzThis

PhoneGap provides detailed documentation, along with example code, for each of the device APIs and data APIs that it supports. I've provided a link to this documentation in the Supplementary Material area.

One of the device APIs that you can access through PhoneGap is the compass. Both iOS and Android operating systems and devices include compass functionality. The purpose of the compass is, naturally, to be able to tell which direction the device is facing.

Let's add a compass to WatzThis.com. Remember that the following code will work only when you convert it into a native app with PhoneGap. I'll show you how to do that in Chapter 4.

Open the latest version of the WatzThis index.html file. After the assignment in Lesson 11, yours may be slightly different, but here's what mine looks like right now. I've taken out the touch functionality and the ghost animation for now because these don't work reliably on all of the native app platforms where I tested them.

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>WatzThis?</title>
<style>
body {
  font-family:arial, helvetica;
  text-align: center;
  }
ol {
    display: inline-block;
    margin: 0 auto;
    text-align:left;
}
.bigButton {
    font-size:18px;
}
#middle {
  background:url("includes/bigback.jpg");
}
#directions, #flashlight, #danceparty {
    margin:4px;
}
#container {
  margin-top: 10px;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
</head>
<body style="margin: 0px; padding: 0px;">
<div id="container">
<div id="top">
<img src="includes/WatzThis-logo.png" width="300px">
</div>
<div id="middle">

<div id="flashlight">
<input type="button" id="OFF" class="bigButton" value="OFF" onclick="flip(0);"> 
<input type="button" id="ON" class="bigButton" value="ON" onclick="flip(1);"> 
<input type="button" id="RED" class="bigButton" value="RED" onclick="flip(2);">     
</div> 
<div id="danceparty"> 
<input type="button" id="AUTO" class="bigButton" value="AUTO" onclick="doAutoFlip(500);"> 
<input type="button" id="STOP" class="bigButton" value="STOP" onclick="stopFlip();"> 
</div>
<div id="geolocation"> 
<input type="button" id="latlong" class="bigButton" value="GET LOC" onclick="getLoc();"> 
</div>
</div>
<div id="bottom">
<div style="margin-top:20px">
	<a href="docs.html"><img src="includes/whatswatzthis.png" width="200"></a>
</div>
<div id="map_canvas"
	style="width: 100%; height: 100%; float: left; border: 1px solid black;">
</div>
</div>
</div>
<script src="includes/watzthis.js"></script>
</body>
</html>

Add the following code to the document header, right after the style element:

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>

 <script type="text/javascript" charset="utf-8">

 // Wait for device API libraries to load
 // 
 
 document.addEventListener("deviceready", onDeviceReady, false);

 // device APIs are available
 //
   function onDeviceReady() {
      navigator.compass.getCurrentHeading(onSuccess, onError);
 }
 
 // onSuccess: Get the current heading
 //
 function onSuccess(heading) {
     alert('Heading: ' + heading.magneticHeading);
 }
     
 // onError: Failed to get the heading
 //
 function onError(compassError) {
     alert('Compass Error: ' + compassError.code);
 }
         
</script>

This code looks for the presence of the PhoneGap (Cordova) framework and whether it's loaded. If it is, the onDeviceReady function uses the compass.getCurrentHeading method to find out which direction the device is pointing. If it can determine this, an alert will pop up in the device and show the current heading. If the heading can't be determined, an alert will pop up and say so.

If you try out this code in a Web browser right now, it won't do anything because PhoneGap isn't present and it's not running in a mobile app. In the next chapter, we'll get the code working.

Android logo

Creating a Native Android App

Two versions of PhoneGap are currently available: PhoneGap and PhoneGap Build.

The full version of PhoneGap is a downloadable framework that works with the APIs and Software Development Kits (SDKs) for the various supported platforms to generate native apps from HTML5 Web apps. To use PhoneGap, you first need to set up your computer as if you were going to develop native apps.

In the case of iOS apps, this means that you need to enroll in the Apple Developer program and pay $99 per year. I won't require you to become an Apple developer for this course, but if you're interested in finding out more, I've put a link in the Supplementary Material.

If you want to develop Android apps, you can simply download the Android SDK using the link in the Supplementary Material.

You can download other native app development kits from the websites of the operating system creator. Besides iOS and Android, PhoneGap can also build native apps for BlackBerry, Windows Phone, webOS (which Palm created and then HP acquired), and Symbian (used on some Nokia phones). Realistically, your app can reach the vast majority of smart phone users by targeting iOS, Android, BlackBerry, and Windows Phone. HP discontinued the development of webOS devices, and Nokia is phasing out Symbian in favor of Windows Phone.

Each of these operating systems has a fundamentally different way of creating native apps. If you decide to go this route for converting your HTML5 apps to native ones, you'll quickly understand why the "write once, deploy anywhere" approach of HTML5 apps is catching on so quickly.

If you don't have the patience for installing SDKs and learning to use each manufacturer's way of developing apps, don't worry about it. PhoneGap has a much easier way of converting your HTML5 apps to native ones, which I'm going to tell you about shortly.

Once you've installed an SDK, the difficult part is done. The next steps are to download the latest version of PhoneGap and then install the version or versions that you'll be creating apps for.

The following figure shows what the PhoneGap framework looks like after you've downloaded and unzipped it:

The unzipped PhoneGap files

Installing an SDK and configuring PhoneGap is beyond the scope of this course, but you can find out exactly what to do by visiting the PhoneGap wiki, which I've linked to in the Supplementary Material.

The downloadable version of PhoneGap gives you the most flexibility in terms of customizing your app. However, if you just want to get something built quickly to see if it works, you can use PhoneGap Build, which is PhoneGap's online service.

Using PhoneGap Build

This service makes creating apps almost as easy as uploading files to a website and clicking a button. While it doesn't give you as much control over how your app is built as you'll get when you download and install the full version, PhoneGap Build is great for getting a taste of the power of converting Web apps into native ones.

In this chapter, I'll take you through the steps to convert WatzThis into native apps for different mobile operating systems.

Before you can upload the app to PhoneGap, you need to package it as a Zip file. If you know how to create a Zip file, go ahead and zip up the latest version of WatzThis, along with all of its supporting files, and name the file watzthis.zip.

If you'd rather have me do the work, you can download watzthis.zipOpens in new window.

Now you're ready to generate your native apps.

  1. Go to Adobe PhoneGap BuildOpens in new window
  2. Click the Get Started button.

    The Adobe PhoneGap Build homepage Get started!

  3. Choose the Free Plan by pressing Completely Free.
  4. You'll be given the choice of registering with an Adobe ID or with Github. Click on with Adobe ID.
  5. If you have an Adobe ID already, you can use the Adobe ID login form to log in.

    Your sign-in options

  6. If you don't have an Adobe ID, click Create an Adobe ID. You'll see a form for creating one.

    Creating an Adobe ID if you don't already have one

  7. Once you're logged in, you'll see the Welcome page.
  8. Click Upload a .zip file, and locate watzthis.zip on your computer.

    Upload your Zip file here.

  9. After you upload the Zip file, you'll see the following screen. Click Ready to build.

    Ready to build!

  10. Phonegap will start to build your native apps. The next screen shows the status of each of the native apps you're building.

Open full size version We're waiting on our apps!

Within a couple of minutes, if all goes well, the waiting icons will all change to icons indicating that the app is finished—all except the iOS one. Remember how I mentioned that you had to pay a $99 fee to build native iOS apps? Yup, that's what's going on here.

If you have an Android, webOS, Windows Mobile, Symbian, or BlackBerry phone, you can browse to your PhoneGap Build account with your phone and download the native app. Once it's on your phone, you can install it and run it like any other app.

Don't have a smartphone? I've included a link in the Supplementary Material to instructions that will allow you to install and run the Android Emulator.

Here's what WatzThis looks like as a native app in Android:

WatzThis native Android app

The popup that appears is triggered by our new native compass code, and it indicates the current direction that the device is pointed, as a number between 0 and 359 (representing each degree of the compass). This picture of a compass will help you figure out how the degree numbers correspond to compass directions.

So in the image that says "Heading: 210," you can tell that the smartphone was facing southwest to south-southwest.

Please move ahead to finish this lesson!

Note: Portions of this page are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

Summary

Here we are at the end of this course! It's just the beginning for the staff of WatzThis.com and for HTML5 mobile apps.

With the app live on the Web and available in the app stores, the entire staff of WatzThis Enterprises is feeling optimistic about the future. They foresee a time when HTML5 Mobile Web apps no longer prompt the question "WatzThis?" and when "write once, run anywhere" is the standard way to build mobile apps.

With your new knowledge of HTML5 mobile app development, you're ready to venture into the world of mobile apps. And that world is expanding and changing rapidly! To help you stay on top of new developments in mobile Web apps, I've included links to some of my favorite sites. Check them out now in the Supplementary Material section and bookmark them.

When you're ready, head on over to the quiz, FAQs, and assignment. Then take the final exam and see just how much you've learned! I think you'll be surprised at what an expert you now are in HTML5 Web apps. And, of course, stop by the Discussion Area and talk about your expertise!

Final Steps

Please don't edit this box. It will automatically update inside the classroom.

Other Courses

Introduction to Ajax Programming

Transform the way your Web applications look and feel! With Ajax programming, you can create applications that provide levels of responsiveness previously unheard of on the Web. In fact, you can use Ajax to develop Web applications that behave and respond just like desktop applications.

In this course, you'll learn each of the technologies that comprise Ajax. We'll spend several lessons digging into JavaScript, a programming language essential to Ajax. You'll discover the wonders of the Document Object Model (DOM), cascading style sheets (CSS), the XMLHttpRequest object, extensible markup language (XML), and PHP scripting. Together, these technologies are what give Ajax its power.

Designing Effective Websites

These days, creating a website is so easy almost anyone can do it. But with all the competition on the Web, creating an effective site is more challenging than ever. In this course, you'll master the basics of Web design and learn how to build sites that are more effective. Get ready to take your Web design skills to the next level!

We'll examine the tension between form and function, explore the six major states of the website development process, and learn the basics of user-centered design. We'll also review the five basic steps to organizing information and talk about how you can use site design themes to deliver information. Along the way, we'll discuss effective type and graphics and explore the idea of Web 2.0.

Advanced CSS3 and HTML5

This course will teach you how to take advantage of HTML5 "semantic" tags that make page design far more intuitive, faster, and easier compared to older versions of HTML. And you'll learn to use HTML5 to create basic mobile pages and apps.

In this class, you'll learn to use HTML5 to provide video that works in any environment. HTML5 makes it possible to build inviting forms that test user data without back-end coding. It also allows designers to include friendly tools like calendars, calculators, and color palettes to encourage accurate user input. You'll leave this course with the skills to create all those elements.

You'll learn to wield new CSS3 features essential for fast-loading, exciting, interactive websites, especially mobile sites. You'll create complex gradient blend backgrounds for pages and page elements, without using image files. And you'll learn to use jQuery Mobile to create app-like mobile Web pages and themes— complex sets of styles for mobile sites. In short, you'll leave this course with valuable skills essential to creating modern websites.

Introduction to JavaScript

You may already know how to use HTML and CSS to create websites. If so, you're ready to add more power to your programming with JavaScript. This programming language lets you add interactivity to your pages by creating features such as buttons, picture carousels, and collapsible panels.

You'll learn how to define what happens when a user clicks a button or presses a key on your pages, and see how JavaScript enables your pages to make "if . . . then . . . else" decisions about what to do based on circumstances. You'll also get a chance to try out loops and timers to create animation effects. Throughout the course, you'll get plenty of hands-on practice.

And since no JavaScript course would be complete without a discussion of jQuery, we cover it as well. This free "write less, do more" JavaScript library has become virtually synonymous with modern Web and mobile app development. By the end of the course, you'll understand how to use jQuery to catapult your basic JavaScript knowledge to incredible new heights.

Supplementary Material

PhoneGap API Documentation

Apple Developer Program - Apple Developer

Download Android Studio and SDK Tools Android Studio

Howto Install and Run the Android Emulator

Home · phonegap phonegap Wiki · GitHub

Smashing Magazine — For Web Designers And Developers — Smashing Magazine

A List Apart For People Who Make Websites

ReadWrite The leading Internet of Things News Platform

PhoneGap App Showcase

Phonegap - Google Groups

Books

Coding with JavaScript For Dummies (For Dummies Series) Chris Minnick, Eva Holland 9781119056072 Amazon com Books

WebKit For Dummies Chris Minnick 9781118127209 Amazon com Books

Beginning HTML5 and CSS3 For Dummies Ed Tittel, Chris Minnick 9781118657201 Amazon com Books

Creating Mobile Apps with jQuery Mobile - Second Edition Andy Matthews, Shane Gliser 9781783555116 Amazon com Books

The Book of CSS3, 2nd Edition A Developer's Guide to the Future of Web Design Peter Gasston 9781593275808 Amazon com Books

Lesson 12 FAQs

Q: Why aren't all apps built with PhoneGap?

A: You make some tradeoffs when you develop apps in HTML5 and convert them to native with PhoneGap. The biggest of these is that it's pretty much impossible to make a Web app behave exactly like a native app. Scrolling is different, and animations and buttons will behave slightly differently, even under the best circumstances.

In the long run, Web apps will very likely achieve the same speed and beauty as native apps, but with the added benefits of using standard Web development skills and being able to run your apps pretty much anywhere.

Q: Are there times when it's better to build native apps rather than convert Web apps to native ones?

A: Opinions vary on this. I believe there are times when a native app just performs better or looks better than a Web app, and the disadvantages of building a Web app outweigh the benefits. There are even times when accomplishing something with a Web app is possible, but it would be more difficult than building the app as a native app.
If you're able to choose what technologies you'll use to build an app, you need to be aware of your options and make a judgment. HTML5 technologies and mobile browsers are improving rapidly, however, and the balance is shifting to Web apps more and more often.

Lesson 12 Assignment

PhoneGap has a large and enthusiastic community of developers and supporters who are constantly working to improve it and show off what can be achieved with HTML5 apps. In this final assignment, I want you to get familiar with this community, and maybe even join in the fun! Now that you're a mobile Web app developer, it's time to take the next step and keep on learning and experimenting.

Go to www.phonegap.com/app/
The PhoneGap App Showcase

Take a look at and read about some of the apps people have built with PhoneGap.
Go to the PhoneGap wiki site
(This link is in the Supplementary Material too.) Then scroll down to the section titled Tutorials.
Read a couple of the tutorials that most interest you.

Go to the PhoneGap Google Group

Read some of the messages. Feel free to join the group, but be warned: Depending on how you set your notification preferences, you could end up getting a lot of mail from this group.
If you wish, please visit the Discussion Area and comment on what you found. Did completing this assignment give you new ideas for apps of your own? What questions do you still have?