Home > Articles > Mobile Application Development & Programming

Creating Mobile Applications for Firefox OS

  • Print
  • + Share This
  • 💬 Discuss
James L. Williams, author of Learning HTML5 Game Programming: A Hands-on Guide to Building Online Games Using Canvas, SVG, and WebGL, shows how to create apps for the Firefox OS platform and how to create a sample application.

The mobile operating system space has several new entrants since the almost total consolidation of the market between Google's Android (and its variants) and Apple's iOS. Firefox OS, formerly Boot2Gecko, is one of those new entrants.

Whereas Android and iOS for the most part require developers to use a compiled language, Java and Objective-C respectively, with some basic support for HTML5 applications, Firefox OS puts HTML5 front and center as the way to create applications.

Open Web Apps Versus Firefox OS Apps

In the Mozilla documentation, it might be confusing to some as there are parts that talk about Open Web Apps in some places and Firefox OS apps in others. Those who have previously developed apps and extensions for Google Chrome might see some similarities and wonder how all compare.

Here's the skinny. An Open Web App and a vanilla Chrome app are similar in that they use HTML, CSS, and JavaScript to drive the application. They also both have JSON manifest files that describe attributes about the app that the browser will use to interact with it. They are close enough in format that it would take little effort to convert one to the other. A Firefox OS app is a specification of an Open Web App. Its manifest can contain a couple more Firefox OS specific attributes like permissions to certain phone features and declaration of activities. It can run on Firefox OS or Android where Firefox is installed. If your app is general enough and you use a utility like Modernizr to do feature detection, you can make an app that runs equally well on desktops and mobiles.

Creating a Weather Application

In this section, I'm going to briefly cover the steps needed to create a weather application. The app uses Wunderground.com APIs for weather information and caches the most recent results in a local database. It covers many of the elements that you will encounter in a typical application. It also uses an Android-themed stylesheet module called holo-web to look more like a native application.

Understanding the Webapp Manifest

As mentioned before, the application manifest file is a JSON file that ends in .webapp and describes how the application will run. Let's discuss it piece by piece.

We begin with the general application information specifying the application version, the name it will be listed as on the device, a description, and which file to run on application boot:

{
  "version": "0.1",
  "name": "Weather App",
  "description": "A Weather App",
  "launch_path": "/index.html",
}
Next, we indicate which icons to be shown at various sizes. Check the documentation for which sizes are required for each platform.
"icons": {
  "16": "images/icons/mortar-16.png",
  "48": "images/icons/mortar-48.png",
  "128": "images/icons/mortar-128.png"
}

Developer information is surfaced when the user first installs the app:

"developer": {
  "name": "James Williams <James.L.Williams@gmail.com>",
  "url": "http://github.com/jwill/informit-articles"
}

The attribute installs_allowed_from specifies a list of domains from which this application can be installed. * permits all domain sources. The snippet also sets English as the default locale. This isn't used in the present manifest, but would be more pertinent if our manifest had localized strings for different locales:

"installs_allowed_from": ["*"],
"default_locale": "en",

Following are the permissions the application will request. In this case, it requests geolocation and the ability to use application storage. You should use the description fields to give an explicit reason why you are requesting the permission.

"permissions": {
  "geolocation":{
    "description": "Required for detecting user location"
  },
  "storage": {
    "description": "Allow user to save location"
  }
}

You can find out more about the other options in a manifest file or see the manifest for the weather app.

Retrieving Remote Assets

As can be expected from its HTML5 roots, retrieving remote assets works no differently than working on a traditional web application. The following snippet retrieves a JSONP set of forecasts for a given location and parses some of the results:

var self = this;
forecast = "//api.wunderground.com/api/"+key+"/forecast/q/"+location+"?callback=?";
$.getJSON(forecast, function(result) {
  var forecasts = result.forecast.txt_forecast.forecastday;
  for (var i = 0; i<4; i++) {
    var fc = forecasts[i];
    $('.desc'+i).get(0).innerHTML = "<span><strong>"+fc.title+"</strong></span><br/>"+fc.fcttext+"<br/><br/>";
    var obj = {title:fc.title, fcttext:fc.fcttext};
    window.localStorage['desc'+i] = JSON.stringify(obj);
  }
});

Working with Storage

Storage in the browser is not difficult, but you are presented with a myriad of choices. IndexedDB, while very robust, requires a bit of setup code to use. To help with these incompatibilities, you can use a library like Lawnchair library to abstract the differences. It implements a key-value store with some helper functions with adapters for different storage types like IndexedDB, localStorage, and WebSQL. With a unified API, changing from one adapter to another is as easy as including a different adapter file. For applications with small amounts of data, using localStorage directly is also a possibility. localStorage is fairly lightweight in terms of operations: getItem, setItem, and removeItem to retrieve, add, and remove an item from the data store. You can also set and retrieve items by indexing the localStorage object as it were a map, as shown here:

var city = window.localStorage['city'];
window.localStorage['state'] = 'CA';
Below is a more full-fledged example using localStorage.
App.prototype.loadWeather = function() {
  if (window.localStorage['city']) {
    var city = window.localStorage['city'];
    var state = window.localStorage['state'];
    $('.location').get(0).innerHTML= city + ', ' + state;
  }
  if (window.localStorage['conditions']) {
    var obj = JSON.parse(window.localStorage['conditions']);
    $('.conditionsText').get(0).innerHTML = obj.conditions;
    $('.conditionsTemp').get(0).innerHTML = obj.temp +" F";
  }
  if (window.localStorage['desc0']) {
    for (var i = 0; i< 4; i++) {
      var obj = JSON.parse(window.localStorage['desc'+i]);
      $('.desc'+i).get(0).innerHTML = "<span><strong>"+obj.title+"</strong></span><br/>"+obj.fcttext+"<br/><br/>";
    }
  }
}

Validating an App

Mozilla runs a web service to validate Firefox OS applications located at http://marketplace.firefox.com/developers/validator (see Figure 1). If you aren't using volo as a build chain, periodically checking you app against the web service can alert you to possible problems early. Not only will you receive a list of errors and warnings, but also you will be advised on how to fix them.

Testing Your Applications

While developing your masterpiece of an application, you will certainly want to test it. Mozilla has got you covered in that respect. There are several means to test your applications. In addition to being able to test them natively on a Firefox OS device (which at time of writing is not available to developers), you can also test on a desktop machine using the Firefox OS Simulator, or on an Android device that has the Mozilla Firefox browser installed.

Firefox OS Simulator

The Firefox OS Simulator (see Figure 2) is an add-on for the Mozilla Firefox web browser that allows you to quickly test your applications.

After installation, you can start the simulator by navigating to Tools, Web Developer, Firefox OS Simulator.

From this view, you can start the simulator or add apps to be installed in the simulator. Unlike simulators and emulators for other platforms like Android and iOS, Firefox OS apps are HTML5 apps, which cause the simulator to start almost instantaneously.

Apps can be added by either selecting a local webapp file (as pictured in Figure 3) or by adding a URL to a remote webapp manifest.

Upon adding an application, the simulator will immediately launch (see Figure 4). If you are working locally and want to view your changes, clicking Update will update the application and relaunch the simulator.

Below is the home screen of the Firefox OS Simulator.

Running on an Android Device

After installing Mozilla Firefox for Android, you can run your app by navigating to the hosted application on a local or publicly accessible server.

Figure 7 shows the weather app running on an Android device.

Using the OpenWebApp App Stubs

On its Marketplace website, Mozilla includes a couple of starter application projects you can work from: a barebones app, an app with a list detail view, and a game stub. By default, the aforementioned examples use volo, a Node.js based build management system and requirejs, which is a JavaScript module loader. While volo has some build tasks that may in some cases be useful, neither library is required to build a Firefox OS application. For the example code with this article, I'll be using some tools with which I'm more familiar.

The only real requirement to test an installed app in the Firefox OS Simulator is the ability to run on port 8008.

Publishing Apps

Firefox has a couple functions in the mozApps namespace of the global navigator object. The most important are the two listed below: install and getInstalled. install takes a URL to a webapp manifest file to install. You can attach handlers to the returned request's onsuccess and onerror properties:

var installRequest = navigator.mozApps.install(mozillaInstallUrl);
  installRequest.onsuccess = function(data) {
  install.triggerChange('installed');
  window.location = 'app.html';
};
installRequest.onerror = function(err) {
  install.error = err;
  install.triggerChange('error');
};

getInstalled retrieves a list of installed applications:

var request = navigator.mozApps.getInstalled();

As an alternative to using install, managing the install flow, and self-hosting your application, you can also upload your application to the Firefox Marketplace.

Conclusion

In this article, we discussed Firefox OS and how to create apps for the platform. We also covered some components needed to create a sample application, and how that application might be distributed. The source for the referenced app is available on Github.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus