Mozilla's getting a new look. What do you think? https://mzl.la/brandsurvey

Soporte de Cordova para Firefox OS

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

El proyecto de Apache Cordova (el cual da poder a la herramienta Phonegap de Adobe) es una solución estandar en la industria para escribir una app con tecnologías web abiertas, y así generar versiones nativas de una app que puedan trabajar sin problemas en otras plataformas como iOS y Android. A partir de la version 3.1, Cordova extiende el soporte para la creación de open web apps que puedan ser instaladas en Firefox OS. Es este articulo veremos como usar la extención de Cordova para Firefox OS, y que beneficios nos trae esto.

Una aplicacion de Firefox OS es basicamente una web app, aunque hay algunas características adicionales, tales como la posibilidad de instalar aplicaciones en plataformas de apoyo y hacer que estén disponibles sin conexión, y el acceso a una variedad de hardware de dispositivo nativo y características a través de algunas APIs especializadas, como la cámara, el hardware de vibración, acelerómetro, alarmas, etc.

Tener normas de Internet para acceder a estas funciones es realmente grande para hacer la plataforma web más potente, pero el problema sigue siendo que el código web no es compatible con las plataformas nativas. La gente está siendo probable que construir para plataformas nativas porque ahí es donde ellos creen que sus esfuerzos se pasan mejor, o utilizar Phonegap para crear diferentes versiones nativas de su aplicación, no teniendo en cuenta las aplicaciones / Open Web App Firefox OS. With Cordova APK for Firefox OS developers have an easy way to output apps for Firefox OS/Open Web App Platform in addition to all the others, creating wrappers and code mappings for the different APIs where appropriate.

 

Configuración del Entorno

The Firefox OS APK has (as of Cordova 3.1) been checked into the main Cordova codebase, so setting up the environment is really simple. First of all you need to install Node.js, then install the Cordova package like so:

npm install -g cordova

Next, create a sample Cordova app and navigate into the newly created directory:

cordova create test-app
cd test-app

Inside this directory you'll see folders that contain the different plugins, and different platform-specific code details. You'll also see a www folder that contains the web code you'll initially write your app into before then compiling it to different native platform code. If you load the index.html file in a browser, you'll see a standard starter template.

Añadir Firefox OS como plataforma de destino

To add different target platforms you use the cordova platform add command followed by the name of the platform in question. Successful creation of native apps also requires having the usual platform tools installed, such as XCode for iOS apps, but Firefox OS doesn't require such environments. For the moment we're only interested in Firefox OS, so run the following command inside your test-app directory:

cordova platform add firefoxos

This creates a Firefox OS app in the platforms/firefoxos/www directory, which currently looks the same except that it has a Firefox manifest file (manifest.webapp) inside the www directory.

At this point you are all set up and ready to go — Firefox OS apps are basically just web apps with extra APIs available and a manifest file, so you don't require extra platform tools to compile them. You can now just change the code inside test-app/www to whatever you want your app to be, then deploy those changes across to the Firefox OS app you've added to your project using

cordova prepare

Simple!

Pruebas y Depuración

  1. The app can be tested directly using the Firefox OS App Manager, like so (this assumes that you have the App Manager set up):
  2. When you have connected the App Manager to your test device/simulator, select the Add Packaged App option, then make sure you point to the test-app/platforms/firefoxos/www/ directory to include the App in the Manager interface.
  3. For here you can install the app on your test device/simulator (with the Update button). Using the Debug button you can then debug the app and edit its code live.

Note: Before attempting to publish your app you should consider validating it using the App Validator. The App Manager provides this functionality by default.

Adding plugins for specific feature support

If you just want to do basic web app stuff then it is pretty simple from here on in, but using native device features and suchlike across different platforms requires use of Cordova plugins. As it stands, Cordova's Firefox OS implementation supports the following plugins:

vibration
Access device vibration hardware
device
Access details of the device's hardware and software, such as model, platform, uuid, etc.
orientation
Control the screen orientation of the app, for example locking it to one orientation
contacts
Access the phone contacts
geolocation
Respond to the location of the device
camera
Use the device's camera
accelerometer
Access the device accelerometer/gyroscope

Note: More will be added going forward; you can go to Apache's Jira system to check out the current state of Cordova Firefox OS plugin implementation.

Construcción de un ejemplo sencillo

Lets build a simple example to show how this works, which makes use of two simple plugins. Starting from the environment we set up earlier, add the above plugins to the project using the following lines:

cordova plugin add org.apache.cordova.device
cordova plugin add org.apache.cordova.vibration

Next, let's add some simple code into the example to make it do something. We'll keep the default code as the icon is kinda cute, but we'll add some simple HTML:

<div class="container dr-list">
  <ol>
  </ol>
</div>

<div class="container vibrate">
  <button>Vibrate</button>
</div>

And some basic CSS to style it:

.container {
    width: 225px;
    margin: 0 0 50px 0;
}

.dr-list li {
    font-size: 1.2em;
    margin-bottom: 5px;
    padding: 5px;
    background-color: rgba(0,0,0,0.3);
    border-radius: 10px;
    box-shadow: inset 2px 2px 5px rgba(0,0,0,0.5);
}

.vibrate button {
    display: block;
    font-size: 1.5em;
    line-height: 1.4;
    width: 110px;
    border-radius: 10px;
    border: none;
    box-shadow: 1px 1px 1px black;
    margin: 0 auto;
    background-image: linear-gradient(to bottom, #ccc, #eee);
}

Note: if you are following along with this, remember to make the changes to the root www project folder, not the version inside platforms/firefoxos.

Now onto the functionality. The device plugin provides a Cordova proprietary device object that hangs off the window object, and allows you to return basic details of the device: let's grab all these values and print them out in an ordered list:

document.addEventListener('deviceready', deviceReadout, false);

function deviceReadout() {
    var drList = document.querySelector('.dr-list ol');
    var drLabels = ['Model', 'Cordova version', 'Platform', 'Device UUID', 'Device version', 'Device name'];
    var drData = [device.model, device.cordova, device.platform, device.uuid, device.version, device.name];
    for(i = 0; i <= drData.length-1; i++) {
      var drListItem = document.createElement('li');
      drListItem.innerHTML = '<strong>' + drLabels[i] + "</strong>: " + drData[i];
      drList.appendChild(drListItem);
    }
}

We wait for Cordova's deviceready event to fire (this happens when Cordova has fully loaded), then loop through arrays containing the device object methods and some labels for them, printing out each pair inside a list item which is placed inside an ordered list.

The other part of the demo is a simple button that, when pressed, makes the phone vibrate for a second: this is pretty self-explanatory:

var vibrateButton = document.querySelector('.vibrate button');
vibrateButton.addEventListener('click', goodVibes, false);

function goodVibes() {
  navigator.notification.vibrate(1000);
}

We can then build the project with

cordova prepare

The app was then tested using the Firefox OS App Manager.

a sample app shown in Firefox OS with some platform data and a vibrate button.

A note on manifest files

Currently the implementation of the manifest.webapp generated by Cordova is reported as invalid by the App Manager: this is because it contains no icon field, so you have to add one to get it to validate:

{
  "launch_path":"/index.html",
  "installs_allowed_from":["*"],
  "version":"0.0.1",
  "name":"My app",
  "pkgName":"io.cordova.hellocordova",
  <strong>"icons": {
    "128": "/img/logo.png"
  }</strong>
}

Also note that to get your custom manifest to persist, you need to save a copy inside the development folder (test-app/www/), otherwise when you run cordova prepare Cordova will overwrite your manifest.webapp again with its default.

So this is good for a start; at this point you can quite easily port it over to another platform — try this:

cordova platform add ios
cordova build ios

a sample app shown in iOS with some platform data and a vibrate button.

Bear in mind that build is needed when you've added a platform like iOS, as iOS code is compiled; however cordova build throws an error when Firefox has been added to the project because Firefox OS code isn't compiled. To make this work more cleanly, you are advised to run this step separately for each platform if possible:

cordova build ios
cordova prepare firefoxos

Publishing your app on the Firefox Marketplace

With your app now created for the Firefox OS platform, you can submit it to the Firefox Marketplace, or pubish it yourself: your choice. Visit the Firefox Marketplace Zone to find out more about how to do this; App publishing options is probably the best place to start.

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Jorge0309, gorrotowi
 Última actualización por: Jorge0309,