Mobile applications with Apache Cordova: access to native resources like accelerometer, GPS location, bluetooth, etc.

For last week I have been reading about developing mobile application using Apache Cordova  because in my work they wanted to develop application for apple and android devices without having to duplicate the code, and this is why I ended up looking at Cordova, because it give you the possibility of developing mobile applications using web technologies like HTML, Javascript and CSS and later on compile them to native code for each one of the platform we want to deploy our application on.

The topics I was more interested in were how to create cross platform mobile applications with capabilities to interact with native resources like accelerometer, location framework (collect the GPS location), bluetooth, and as well get access to functionalities like execute the application on background mode to being able to keep communicating with these devices even if the user open other applications and our application is sent to the background. The reason why I was interested in these capabilities is because it would be straightforward make a purely Web application with any requirement to interact with the native APIs of the platform where the application is running, for those type of application we do not need things like Cordova.

As result, I decided to write this post sharing with anyone interesting what I have learnt, including a sample application I wrote to test the Cordova capabilities I mentioned above.

 

Pre-requisites

Because Cordova compiles to native code it needs the native SDK environment for each platform the application will have to compile to, for example, if the application needs to support IOS and Android devices like the case of the sample application developed for this document, the Xcode environment for IOS and Android Studio will have to be installed.

The Xcode is the official environment for developing applications for apple devices, and can be installed using the AppStore or downloaded from  “https://developer.apple.com/xcode/“. This tool is a good option as well for managing the developer certificates required to execute the applications in real devices.

For Android, the list of pre-requisites needed to install are:

  1. Android Studio ( https://developer.android.com/studio/index.html ).
  2. Android File transfer ( https://www.android.com/filetransfer/ ): if using a MAC OS as development environment, this tool is necessary for installing the application in android devices, because MAC Os does not detect automatically these devices when they are plugged unless the android file transfer application is running.
  3. Install the google Apis using the android studio  sdk manger (Tools->Android->SDK Manager).

AndroidStudio.png

Cordova concepts and installation

To understand the structure of the Cordova platform the diagram available with the official documentation can be very descriptive. As the picture shows, Cordova applications are written using web technologies like HTML, JavaScript, CSS, and if they needs access to low level resources from the device, or access to any functionality exposed by the device native API  this is achieved using the Cordova APIs.

cordovaapparchitecture

For a deeper overview of Cordova it is highly recommendable go through the official documentation, here we move directly to the steps to install the Cordova command line tool and create a project.

  1. Cordova command line is a Node.js application and can be installed using the npm command.

                   npm install -g cordova
 

2. Install ios-deploy

                 npm install -g iso-deploy
 

3. Once the cordova command line installed projects can be created.

                 cordova create samplecordovaapp com.ecollado.training.cordova SampleCordovaApp

4. The platform the application will have to support can be added now

              cordova platform add ios –save
cordova platform add android –save
 

5. To execute the application in the emulators

               cordova emulate [ ios | android ]

6. And to execute the application in the real devices.
               cordova run [ios | android ]

 

The command above will create the application within the folder “samplecordovaapp”, containing a sub-directory “www” where the web application is located. The native project for each platform is available as well under the folder platforms, this project can be opened by the native environment like Xcode for IOS.

Plugins

 

The Cordova APIs giving access to the low level resources are implemented as plugins, therefore, each time the application needs to use a new functionality from the OS, the developer should look for the proper plugin, add it to the project and then use the javascript api exposed by the plugin. The Cordova documentation contains information about a list of plugins (battery status, camera, contacts, etc) but more are available through the plugin search site (https://cordova.apache.org/plugins/).

One essential plugin can be the console one, allowing us to write message to the console using the java script function “console.log()“. To add this plugin to our just created project we can type in the command line:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

Once added the plugin to the project the javascript function showed above can be used to print traces in the console, and for example if the application is running in an IOS device attached to the Xcode the messages will appear in the Xcode console.

Device ready javascript event

Most of the Cordova APIs (or maybe all of them) needs to wait until the cordova core libraries have been loaded and are ready to be invoked, and this is notified to the cordova application by a concrete event named “deviceready”, therefore it could be said that this event is the main method for the cordova application. Taking this into account the minimum javascript code every cordova application should have could be similar to the example below.

var app = {
// Application Constructor
initialize: function()
{
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},

// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function()
{
console.log("cordova core libraries have been initialised");
}
};

app.initialize();

Sample application

As said before, there is a sample application published in github, where it can be seen how to used the cordova APIs to use devices like (source javascript file index.js):

  1. Bluetooth LE: using the plugin “cordova-plugin-bluetoothle”.
  2. Accelerometer: using the plugin “cordova-plugin-device-motion“.
  3. Location: using the plugin “cordova-plugin-geolocation“.

Screen orientation.

The screen orientation can be detected on android devices using the javascript event “orientationchange” as it can be seen in the source code file indicated above. For IOs devices is more complex because that listener does not work (it seems the UIWebView component used by Cordova to embed the application in a web container does not support sit.) reason why it is needed to use the plugin cordova-plugin-device-orientation“, to use the compass to detect rotation devices changes and check the screen status, like for example the code below.


...
if (platform === "iOS")
{
// Initialize the view with the current screen dimensions
onOrientationChange();
var watchID = navigator.compass.watchHeading(onOrientationChange, compassError, { filter: 10 });
}
...

function onOrientationChange(result)
{

    var physicalScreenWidth;
    var physicalScreenHeight;

    if (screen.orientation === 'portrait-primary')
    {
        if (window.screen.width > window.screen.height)
        {
            physicalScreenWidth = window.screen.height;
            physicalScreenHeight = window.screen.width;
        }
        else
        {
            physicalScreenWidth = window.screen.width;
            physicalScreenHeight = window.screen.height;
        }
    }
    else if (screen.orientation === 'landscape-primary')
    {
        if (window.screen.width < window.screen.height)
        {
            physicalScreenWidth = window.screen.height;
            physicalScreenHeight = window.screen.width;
        }
        else
        {
            physicalScreenWidth = window.screen.width;
            physicalScreenHeight = window.screen.height;
        }
    }

    physicalScreenHeight *= window.devicePixelRatio;
    physicalScreenWidth *= window.devicePixelRatio;

    var widthElement = document.getElementById('screen_width');
    widthElement.innerHTML = physicalScreenWidth;

    var heightElement = document.getElementById('screen_height');
    heightElement.innerHTML = physicalScreenHeight;
}
 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s