Firefox OS app beginners tutorial
Abdur Rahman Joy
Creative Designer, UI / UX designer, Motion Graphics Designer, 3D & 3D Animator, Apps Developer, Senior IT Trainer for GAVE( ISDB Besew) at Star Computers ltd, Senior IT Trainer for J2EE, Software Testing at PeopleNTech
Firefox OS app beginners tutorial
Firefox OS apps are essentially no different to standard websites or web apps. They are built using standard open web technologies — HTML, CSS, JavaScript, etc. — and can be accessed using a web browser. The main differences lie in their ability to be installed on devices and work offline, access to advanced APIs that allow interaction with device features such as camera, gyroscope and address book, and the existance of a solid developer ecosystem — including a Marketplace for distribution of free and paid apps. Generally, they provide users with an "app experience", while still being based on open, cross platform technologies.
Firefox OS apps have a low barrier for entry, especially for existing web developers and mobile developers; they are also a lot more portable across platforms than native equivalents, and not locked into walled gardens.
Firefox OS
Firefox OS (also referred to by its codename Boot to Gecko — or B2G) is Mozilla's open source mobile operating system. It's based on a Linux kernel, which boots into a Gecko-based runtime that lets users install and run open web apps, Gecko being the rendering engine that the Firefox browser uses to render and display web content.
Firefox OS comes with a suite of pre-installed applications called Gaia, which handles the fundamental functions of the phone such as settings, calls, SMS, taking and storing photos, etc.
Skills Needed
As we've already mentioned Firefox OS apps are based on web technologies — HTML, CSS, and JavaScript — so if you've written a web page you already know the basics. Even if you don't have the basics you'll be able to easily follow this guide, but you may want to check out our list of Beginner's tutorials to learn more about developing with open web technologies.
Required Tools
You can build Firefox OS apps with simple free tools, or make use of your existing web editing tools. We'd suggest getting hold of:
? A simple text editor such as Sublime Text (trial for free), Gedit (free), Notepad++ (free), Atom (free) or Brackets (free, and built with HTML, CSS, and JavaScript), or a more complex IDE such as Eclipse (free), Netbeans (free) or Dreamweaver.
? Firefox and other modern browsers to test your app. Firefox comes with a set of very useful standard debugging tools, and also provides the Firefox OS App Manager to further aid with testing.
Once you get started you will want to run your web app on a Firefox OS phone; you can get a developer preview device or install your own build on an existing device, such as various supported Google Nexus models.
Your first app
This section aims to get you up and running quickly with an installable web app, showing you how quick and easy it is to learn the basics. If you'd like to follow along with this guide, you can find our quickstart starter template repo on Github (download directly as a zip).
Quickstart app starter template
Our app does something very simple — it uses the Battery Status API to fetch the battery charge level of the device and check to see whether the battery is charging or not, and alerts the user to the status of this via a vibration (via the Vibration API) and system notification (via the Notification API).
To begin with, the starter template directory has the following structure:
? battery-quickstart-starter-template/
o index.html
o images/
? battery.svg
? icon-128.png
? icon-512.png
o scripts/
? battery.js
? install.js
o style/
? style.css
o .htaccess
o README.md
? index.html : The main document of our app that contains its content, and which everything else feeds into.
? images : Contains an icon used in the app UI, plus the app icons for display on the Firefox Marketplace (if submitted there) and homescreen of the devices the app is installed on (and potentially other places too). For more information on app icons, read our Icon implementation for apps guide.
? scripts : Will contain the JavaScript code that defines the functionality of the app; currently there are two blank files — battery.js and install.js.
? style : contains a stylesheet, style.css, to provide the app with basic styling.
? .htaccess: A server config file that informs web servers of the mime type of the manifest file we are adding in the next section. This makes sure that servers don't throw an error if they don't recognise the manifest file type (which some might.)
? README.md: Markdown-based readme file that Github uses to explain what this repo is all about.
Adding a manifest
Every open web app requires a manifest.webapp file to be placed in the app's root folder: This provides important information about the app, such as version, name, description, icon location, locale strings, domains the app can be installed from, and much more.
Add the following into a new plain text file in your app's root. Name the file manifest.webapp.
{
"name": "Battery",
"description": "Battery provides a good template for an in-app battery/charge indicator with different visualization choices, plus ideas of what could be changed once battery level gets low.",
"launch_path": "/index.html",
"icons": {
"128": "/images/icon-128.png",
"512": "/images/icon-512.png"
},
"developer": {
"name": "Chris Mills",
"url": "https://www.conquestofsteel.co.uk"
},
"permissions": {
"desktop-notification": {
"description": "Needed for creating system notifications."
}
}
}
Note: For more information on exactly what is going on here, consult our App Manifests reference.
Note: paths in manifest files should be relative to the origin of the server location. So for example, if my example's root is at https://www.mysite.com/myapp/, and my icon is at https://www.mysite.com/myapp/myicon/icon.png, the icon path would be /myapp/myicon/icon.png, not /myicon/icon.png.
API permissions
There are a number of WebAPIs available that require permissions for that specific feature to be enabled. Installed apps have to register permission requests within the manifest.webapp file as seen in the "permissions" field above, which requests permission to use the system notifications controlled by the Notification API.
Different APIs require different levels of permission to access them. The three levels of permission are as follows:
1. Normal — APIs that don't need any kind of special access permissions.
2. Privileged — APIs available to developers to use in their applications, as long as they set access permissions in the app manifest files, and distribute them through a trusted source.
3. Certified — APIs that control critical functions on a device, such as the call dialer and messaging services. These are generally not available for third party developers to use.
Note: For more information on what APIs require what permissions, read App permissions.
Web API functionality
JavaScript APIs are being created and enhanced as quickly as devices are. Mozilla's WebAPI effort brings dozens of standard mobile features to JavaScript APIs.
Detecting support for features
One technique employed commonly in web development is JavaScript feature detection — it involves running code to make sure a feature is supported by the browser before you actually try to use that feature. If it doesn't, you can provide some kind of fallback experience. The following snippet provides a quick example (this doesn't need to be added into your example code):
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.log("This browser does not support notifications.");
}
Our code for the quickstart example functionality
Inside the scripts/battery.js file, add the following code blocks one after the other, reading the code comments carefully as you go. First, we'll set up all the variables we need:
// fork the navigator.battery object depending on what prefix the viewing browser uses
var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
// grab the elements we need, and put them in variables
var indicator1 = document.getElementById('indicator1');
var indicator2 = document.getElementById('indicator2');
var batteryCharge = document.getElementById('battery-charge');
var batteryTop = document.getElementById('battery-top');
var chargeIcon = document.getElementById('battery-charging');
// Flag to check if battery charged/not charged has already been notified once
// 0 for first time of notification,
// 1 means "charged" has already been notified,
// 2 means "not charged" has already been notified
// This is set to the opposite after each notification, so that you don't keep
// getting repeat notifications about the same charge state.
var chargingState = 0;
Next, we'll add the main updateBatteryStatus() function, which is responsible for updating the displayed information about the battery's status whenever a battery-related event is fired:
function updateBatteryStatus() {
// battery.level can be used to give us a percentage of bettery charge to report to
// the app's user
var percentage = Math.round(battery.level * 100);
indicator1.innerHTML = "Battery charge at " + percentage + "%";
batteryCharge.style.width = percentage + '%';
if(percentage >= 99) {
// report that the battery is fully charged, more or less ;-)
batteryTop.style.backgroundColor = 'limegreen';
batteryCharge.style.backgroundColor = 'limegreen';
createNotification("Device battery fully charged.");
}
if(battery.charging) {
// If the battery is charging
if(chargingState == 1 || chargingState == 0) {
// and if our chargingState flag is equal to 0 or 1
// alter the styling to show the battery charging
batteryTop.style.backgroundColor = 'gold';
batteryCharge.style.backgroundColor = 'gold';
indicator2.innerHTML = "Battery is charging";
chargeIcon.style.visibility = 'visible';
// notify the user with a custom notification
createNotification("Device battery now charging.");
// flip the chargingState flag to 2
chargingState = 2;
}
} else if(!battery.charging) {
// If the battery is NOT charging
if(chargingState == 2 || chargingState == 0) {
// and if our chargingState flag is equal to 0 or 2
// alter the styling to show the battery NOT charging
batteryTop.style.backgroundColor = 'yellow';
batteryCharge.style.backgroundColor = 'yellow';
indicator2.innerHTML = "Battery not charging";
chargeIcon.style.visibility = 'hidden';
// notify the user with a custom notification
createNotification("Device battery is not charging.");
// flip the chargingState flag to 1
chargingState = 1;
}
}
}
Now it's time to add in the createNotification() function referenced above. When this is called, a system notification is fired containing the message passed in as its argument. This code seems a bit long-winded, but here we are both detecting support for Notifications, and handling bulletproof support for both Firefox and Chromium/Blink-based browsers.
function createNotification(message) {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.log("This browser does not support notifications.");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
// show the notification
var notification = new Notification('Battery status', { body: message });
// And vibrate the device if it supports vibration API
window.navigator.vibrate(500);
}
// Otherwise, we need to ask the user for permission
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure Chrome stores the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
// show the notification
var notification = new Notification('Battery status', { body: message });
// And vibrate the device if it supports vibration API
window.navigator.vibrate(500);
}
});
}
}
Finally, we'll add event handlers to the battery object to let us respond to changes in the battery's charging state and charge level (by running the updateBatteryStatus() function), and then run updateBatteryStatus() once to get the show started:
// Event handler to check whether the battery has started charging or stopped charging
battery.addEventListener("chargingchange", updateBatteryStatus, false);
// Event handler to check whether the battery charge level has changed
battery.addEventListener("levelchange", updateBatteryStatus, false);
// run the central function once when the app is first loaded
updateBatteryStatus();
The comments should explain what the code does well enough, but the take home message is that it is easy to use hardware data and functionality via such APIs, with simple events and objects like chargingchange, battery, and Notification().
The JavaScript is watching for when the battery charge level changes, or when the battery stops or starts charging (the chargingchange and levelchange event listeners.) When one of these events happens, the updateBatteryStatus() function is run, which decides what notification to tell the user, updates the visual display to suit, and runs createNotification().
This final function actually fires the system notification and makes the phone vibrate to give the user some extra system-wide feedback as to what the battery status is.
Note: Check the WebAPI page frequently to keep up to date with device API statuses.
Learn more:
please visit the following urs: