Get in Touch
Services
Chat
0203 884 1100

How To Develop Cross Platform Mobile Applications with Cordova ?

Nowadays mobile app development or cross platform mobile app is crawling in everyplace, beginning with smartphones and tablets, to good watches, and shortly be found in alternative wearables, too. H

owever, developing for every separate cross platform mobile app development will be a complete task, mainly if your resources are restricted, or if you’re one develop

 

cross platform mobile app development

By providing the way using conventional web technologies—HTML5, CSS3, and JavaScript, a well-versed Apache Cordova developer, are available handy to develop cross-platform mobile applications.

 

Understanding the fundamentals:

 

What is Cordova?

Apache Cordova could be a framework for making cross platform mobile app development using conventional web technologies.

 

Primarily, it’s an application container with a web read that covers the complete screen of the device.

 

What is PhoneGap?

Nowadays, PhoneGap refers to a product engineered by Adobe on top of Apache Cordova.

 

 

 

Initially, it had been the framework created by Nitobi before Adobe acquired them and open-sourced it as Apache Cordova.

 

What is WebView?

Android’s Web View and iOS’ UI Web View are the categories the individual operating systems use to show web content full-screen. App Developers will build web browsers with them, and use them to show a web app as if it were a native app.

 

What is a Cordova plugin?

Apache Cordova plugins provide any access to cross-platform options. These are often hardware-based services like geolocation or purely software-based functionality like OS-provided SQLite database access.

 

mobile app development and cross platform mobile app development

 

 

An open source API, at startup PhoneGap, created Nitobi for accessing native mobile resources, with the goal of enabling app developers to make mobile applications using conventional net technologies.

Most mobile applications would before long be developed using PhoneGap by nitobi it minimise, however, developers would still have the choice of writing native code once necessary, be it because of performance problems, or lack of a way of accessing specific hardware.

 

Cordova With PhoneGap:

There’s no such factor. What happened was, Adobe acquired Nitobi in 2011 and given the open-source core to the Apache computer code Foundation, who rebranded it, Apache Cordova. a common analogy you may usually run into is that Cordova is to PhoneGap what WebKit is to Chrome or Safari.

Apparently, the variations between Cordova and PhoneGap were minimal within the starting. With time, Adobe PhoneGap developed its own set of proprietary options, whereas Cordova was—and still is—supported by the open-source community.

The review and tutorial of Apache Cordova can examine Cordova app development in additional detail, and whereas a number of it should apply to PhoneGap, this shouldn’t be thought-about a PhoneGap tutorial.

 

Capabilities Of Apache Cordova:

In essence, Cordova has no limitations concerning natively developed applications. What you get with Cordova is solely a JavaScript API, that is a wrapper for native code and is consistent across devices.

 

 

mobile app development and cross platform mobile app development

 

 

You’ll take into account Cordova to be an application container with an online read, which covers the whole screen of the device. The web read utilized by Cordova is that the same web read utilized by the native operating system.

On iOS App Development, this is often the default Objective-C UI Web View or a custom WK Web View class; on Android, this is often android.web kit.Web View.

Apache Cordova comes with a group of pre-developed plugins which give access to the device’s camera, GPS, file system, etc.

As mobile devices evolve, adding support for extra hardware is solely a matter of developing new plugins.

Finally, Cordova applications install rather like native applications. This implies that building your code for iOS app Development can manufacture an IPA file, for android an APK file, associate degreed building for Windows Phone produces a XAP file. If you place enough effort into the event method, your users may not even understand that they’re not using a native application.

 

Workflow Of Apache Cordova Development:

There are 2 primary methods you’ll follow once developing with Cordova:

Once you intend to deploy an application to as several platforms as doable, with very little or no platform-specific app development, you ought to use the cross-platform app development progress.

 

 

mobile app development and cross platform mobile app development

 

 

The most tool in progress supports the Cordova Command-Line Interface (CLI), that is the next level abstraction for configuring and building your application for various platforms.

This is often the new customarily used development path.

If you propose to develop your mobile application with a selected platform in mind, you ought to use the platform-centered progress. To tweak and modify your code you might ready by this way at a lower level by admixture native elements with Cordova elements.

Albeit you’ll use this approach for cross-platform app development, the method is going to be longer and additional tedious.

It is sometimes counselled to start out with the cross platform mobile app development since the shift to platform-centered development is relatively easy.

However, if you at the {start} start with the platform-centered progress, {you can|you’ll|you may} not be ready to switch to cross-platform development since the interface will write your customizations once you run the build method.

 

Cordova Installation and Prerequisites:

Before putting in and running something associated with Cordova, you may have to be compelled to install the SDK for every platform that you shall build your application form.

We’ll concentrate on the Andriod app development platform during this article; but, the method involving alternative platforms is analogous.

You should download the Android app development SDK found here. For Windows app development, the SDK comes as an installer, whereas for Linux and OSX it comes as an archive which may be merely extracted.

Once extracting/installing the package:

You may have to be compelled to add the SDK/tools and SDK/platform-tools directories to your PATH variable. The trail variable is used by Cordova to appear for the binaries it wants for the build method.

If you don’t have Java put in, you ought to plow ahead and install the JDK at the side of pismire. ANT_HOME and JAVA_HOME ought to be set to the bin folders of JDK and pismire, and once putting in the Android SDK, set the ANDROID_HOME variable to Android/SDK.

All locations within the 3 *_HOME variables ought to even be in your PATH variable.

After you put in the SDK android command can become offered in your statement. Execute it to open the SDK manager and install the newest tools and Android API.

You’d probably like Android SDK Tools, robot SDK Platform-tools, Android SDK Build-tools, SDK Platform, Google APIs Intel x86 Atom System Image, Sources for Android SDK and Intel x86 soul Accelerator (HAXM installer). Subsequently, you may be ready to produce a soul with android avd.

 

Cordova interface depends on Node.js and therefore the bum consumer, thus move and transfer and install Node from nodejs.org, and git from git-scm.com.

You may be using npm to put in Cordova interface itself yet as for putting in extra plugins, and Cordova can use bum behind the scenes to transfer needed dependencies.

Finally, run
npm install -g cordova
…to install the Cordova CLI globally (npm install cordova isn’t sufficient by itself.)

To summarise, these are the packages that you can need:
• Java
• Ant
• Android SDK
• NodeJS
• Git

And these surroundings variables can have to be compelled to be updated:

• PATH
• JAVA_HOME
• ANT_HOME
• ANDROID_HOME

 

An Application Bootstrapping:

Provided you have got with success put in Cordova, and you ought to currently have access to the Cordova statement utility.

For navigation to a directory, you have to open your terminal or command-line, wherever you’d wish to produce your initial Cordova project.

To bootstrap an application, sort within the following command:

cordova create techtiq techtiq.hello HelloTechtiq

 

The statement consists of the name of the command Cordova, following by the sub-command produce. The sub-command is invoked with three extra parameters: The folder wherever the applying are going to be placed, the namespace of the applying, and its show name.

 

This bootstraps the applying in an exceeding folder with the following structure:

techtiq/
|– hooks/
|– platforms/
|– plugins/
|– www/
`– config.xml

 

The web folder contains your application core. This is often wherever you may place your mobile application development code that is common for all platforms.

 

While Cordova permits you to just develop an app for various platforms, generally you would like to feature customizations.

 

Once developing for multiple platforms, you don’t need to switch the supply files within the diverse platforms/[platform-name][assets]/www directories, as a result of they’re frequently overwritten with the top-ranking web files.

 

At now you’ll additionally open up the config.xml file and alter the information for your application, like author and outline.

Add your first platform using:

 

cordova platform add android

If you modify your mind afterwards, you’ll take away a platform from the build method easily:

cordova platform rm android

Upon inspecting the platforms directory, you may notice the android folder among it. For every platform that you add, Cordova can produce a replacement directory in platforms and duplicate the web folder among it.

If, for instance, you would like to customize your application for Android, you’ll modify the files in platforms/android/assets/www and switch to platform-specific shell tools.

 

However, keep in mind that if you reconstruct your application with the interface (used for cross platform mobile app development), Cordova can write the changes you have got created for every platform, thus either certify you have obtained them underneath version management.

 

Otherwise, you do platform-specific changes once you have got finished with cross-platform development. As we tend mentioned earlier, moving from cross-platform to platform-specific development is straightforward. Reaching the opposite direction isn’t.

You ought to use the top-ranking merges folder when you would like to stay using the cross-platform progress and still build platform-specific customizations.

From Cordova version three.5 onward, this folder has been off from the default application model, and however if you would like it, you’ll merely produce it aboard the different top-ranking directories (hooks, platforms, plugins, and www).

Platform-specific customizations are placed in merges/[platform-name] and are applied once the supply files within the top-ranking web folder. This way, you’ll either add new supply files indeed platforms. Otherwise, you will override entire top-ranking supply files with platform-specific ones.

 

Take the following structure for example:
merges/
|– wp8/
| `– app.js
|– android/
| `– android.js
|– www/
`– app.js

In this case, the output file for android can contain each the app.js and robot.js files. However, the output file for Windows Phone eight can solely contain the app.js file that is found within the merges/wp8 folder since the files in merges/[platform] override the files in WWW.

 

The plugins directory contains data for every platform’s plugins. At now, you ought to solely have the android.json file that ought to have the following structure:
{
“prepare_queue”: {
“installed”: [],
“uninstalled”: []
},
“config_munge”: {
“files”: {}
},
“installed_plugins”: {},
“dependent_plugins”: {}
}

Let us build the mobile app and deploy it to an Android device. You’ll use the emulator too if you would like.

For building and running your apps, Cordova provides many CLI steps: Cordova prepare, Cordova compile, Cordova build (which could be a shortcut for the previous two), Cordova emulate, and Cordova run (which incorporates build and might run aper too).

 

This could not confuse you, as a result of in most cases you’d wish to develop and run your app within the emulator:

cordova run –emulator

If you would like, you’ll plug your device in through the USB port, modify USB debugging mode and deploy your initial Apache Cordova application straight to your device merely running:

cordova run
This will copy all of your files into platforms/* and execute all needed tasks.

You can limit the scope of the build method by specifying the name of the platform that you would like to make the application and/or even the precise emulator, e.g:

cordova run android –emulator
or
cordova run ios –emulator –target=”iPhone-8-Plus”

 

Apache Cordova Tutorial:

Let’s create an easy tutorial application to demonstrate the employment of Cordova and its plugins. The whole demo is often found during this GitHub repository so that you’ll download it and go through elements of it at the side of this short Cordova tutorial.

We will use the initial setup you created and add extra code. Let’s say that we would like to feature new comes to an imagined information, moreover as read existing ones.

 

Open up index.html and set up 2 tabs within the following manner:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″ />
<meta name=”format-detection” content=”telephone=no” />
<meta name=”msapplication-tap-highlight” content=”no” />
<meta name=”viewport” content=”user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi” />
<link rel=”stylesheet” type=”text/css” href=”css/bootstrap.min.css” />
<link rel=”stylesheet” href=”css/jquery.mobile-1.4.5.min.css” />
<link rel=”stylesheet” type=”text/css” href=”css/toptal.css” />
<title>Hello Toptal</title>
</head>
<body>
<div id=”container”>
<div id=”tab-content”>

</div>
</div>
<footer>
<ul id=”menu”>
<li id=”search-tab-button” class=”tab-button active” data-tab=”#search-tab”>Search Projects</li>
<li id=”post-tab-button” class=”tab-button” data-tab=”#add-tab”>Post a Project</li>
</ul>
</footer>
<div id=”dev-null” style=”display: none”></div>
<script src=”js/lib/jquery-1.11.1.min.js”></script>
<script src=”js/lib/jquery.mobile-1.4.5.min.js”></script>
<script type=”text/javascript” src=”cordova.js”></script>
<script type=”text/javascript” src=”js/SQLiteStorageService.js”></script>
<script type=”text/javascript” src=”js/Controller.js”></script>
<script type=”text/javascript” src=”js/index.js”></script>
</body>
</html>

Notice that I have added Bootstrap and jQuery Mobile as dependencies. Please remember that far better solutions and frameworks are developed for building trendy hybrid applications,

 

however, since most (if not all) web development developers are aware of these 2 libraries, it is smart to use them for a beginners’ tutorial. You’ll be able to transfer the stylesheets from GitHub or use your own if you favour.

 

Let us move to the index.js file, and strip it down to the following:

var app = {
// Application Constructor
initialize: function() {
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener(“deviceready”, this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},

onDeviceReady: function() {
// We will init / bootstrap our application here
},
};
app.initialize();

Architecture for Cordova applications is advocated and fixed one Page Application which you have to remember (SPA). This way, all of the resources are solely loaded once the app starts, and may keep within the web read for as long because the application is running.

 

Additionally, with SPAs, the user won’t have page reloads that aren’t merely typical for native applications.

Keeping that in mind, allow us to originated a straightforward controller to change between the 2 tabs:
var Controller = function() {
var controller = {
self: null,
initialize: function() {
self = this;
this.bindEvents();
self.renderSearchView();
},

bindEvents: function() {
$(‘.tab-button’).on(‘click’, this.onTabClick);
},

onTabClick: function(e) {
e.preventDefault();
if ($(this).hasClass(‘active’)) {
return;
}

var tab = $(this).data(‘tab’);
if (tab === ‘#add-tab’) {
self.renderPostView();
} else {
self.renderSearchView();
}
},

renderPostView: function() {
$(‘.tab-button’).removeClass(‘active’);
$(‘#post-tab-button’).addClass(‘active’);

var $tab = $(‘#tab-content’);
$tab.empty();
$(“#tab-content”).load(“./views/post-project-view.html”, function(data) {
$(‘#tab-content’).find(‘#post-project-form’).on(‘submit’, self.postProject);
});
},

renderSearchView: function() {
$(‘.tab-button’).removeClass(‘active’);
$(‘#search-tab-button’).addClass(‘active’);

var $tab = $(‘#tab-content’);
$tab.empty();

var $projectTemplate = null;
$(“#tab-content”).load(“./views/search-project-view.html”, function(data) {
$projectTemplate = $(‘.project’).remove();
// Load projects here
});
}
}
controller.initialize();
return controller;
}

Two methods are there for controllers so far, one for rendering the Post Project view and another for rendering the Search View, and. We have to initialise it in our index.js file by first declaring it at the top and constructing it in the on

Device Ready method:

// top of index.js
var controller = null
// inside on Device Ready method
controller = new Controller();

Finally, add a script reference in index.html higher than the relation to index.js. You’ll download the Search and Post views directly from GitHub.

Since the partial views are a scan from a file, some browsers like Chrome, whereas attempting to render your page, can complain concerning cross-domain requests

The attainable answer here would be to run a local static server, as an example mistreatment the node-static npm module. Also, here you’ll begin considering using some framework like PhoneGap and/or Ionic App Development.

All of them give a variety of development tools, as well as emulating in the browser, hot reloading, and code generating (scaffolding).

For now, let’s merely deploy to an Android device by running the following:

 

cordova run android

At this time, your application ought to have 2 tabs. The original tab permits come to be searched:

 

 

The second tab permits new comes to be posted:

 

 

 

 

All we’ve got now could be a classic net application running within a web read. We have a tendency to haven’t very used any of the native options, therefore, let’s try and try this currently.

A typical question is a way to store knowledge locally on the device, or a lot of correctly, what kind of storage to use.

There square measure many ways in which to go:

• LocalStorage
• WebSQL
• IndexedDB
• Server-side storage accessed through a web service
• Third-party plugins providing different choices

Local-Storage is OK for storing tiny amounts of information. However, it won’t satisfy if you’re building a data-intensive application, because the available space varies from three to ten MB. IndexedDB is also a far better answer for this case.

WebSQL is deprecated and not supported on some platforms. Finally, using web services to fetch and modify knowledge fits well inside the SPA paradigm

However, it breaks down once your application goes offline. PWA techniques in conjunction with Service staff has recently get Cordova world to assist with this.

Also, there are heaps of extra, third-party plugins that are available in to fill the gaps in Cordova’s core.

The File plugin is also quite helpful because it provides you with access to the device’s filing system, permitting you to make and store files.

For now, let’s strive SQLitePlugin that provides you with an area SQLite info.

 

You’ll add it to your project by running:

 

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin

 

SQLitePlugin provides AN API to the device’s SQLite info and is a real persistence mechanism. We will produce a straightforward Storage Service within the following manner:
SQLiteStorageService = function () {
var service = {};
var db = window.sqlitePlugin ?
window.sqlitePlugin.openDatabase({name: “demo.toptal”, location: “default”}) :
window.openDatabase(“demo.toptal”, “1.0”, “DB para FactAV”, 5000000);
service.initialize = function() {
// Initialize the database
var deferred = $.Deferred();
db.transaction(function(tx) {
tx.executeSql(
‘CREATE TABLE IF NOT EXISTS projects ‘ +
‘(id integer primary key, name text, company text, description text, latitude real, longitude real)’
,[], function(tx, res) {
tx.executeSql(‘DELETE FROM projects’, [], function(tx, res) {
deferred.resolve(service);
}, function(tx, res) {
deferred.reject(‘Error initializing database’);
});
}, function(tx, res) {
deferred.reject(‘Error initializing database’);
});
});
return deferred.promise();
}

service.getProjects = function() {
// fetch projects
}

service.addProject = function(name, company, description, addLocation) {
// add a new project
}

return service.initialize();
}

You can download the code for fetching and adding projects from GitHub and paste it in the respective placeholders. Do not forget to add SQLiteStorageService.js to your index.html file above Controller.js, and initialise it in your controller by modifying the Controller’s init function:

initialize: function() {
self = this;
new SQLiteStorageService().done(function(service) {
self.storageService = service;
self.bindEvents();
self.renderSearchView();
}).fail(function(error) {
alert(error);
});
}

If you take a glimpse at the service.addProject(), you will notice that it makes a call to the navigator.geolocation.getCurrentPosition() method.

 

mobile app development and cross platform mobile app development
Geo location

 

 

Cordova has a geolocation plugin which you can use to get the phone’s current location, and you can even use the navigator.geolocation.watchPosition() method to receive updates when the user’s position changes.

Finally, let’s add the controller event handles for adding and fetching projects from the database:

renderPostView: function() {
$(‘.tab-button’).removeClass(‘active’);
$(‘#post-tab-button’).addClass(‘active’);

var $tab = $(‘#tab-content’);
$tab.empty();
$(“#tab-content”).load(“./views/post-project-view.html”, function(data) {
$(‘#tab-content’).find(‘#post-project-form’).on(‘submit’, self.postProject);
});
},

postProject: function(e) {
e.preventDefault();
var name = $(‘#project-name’).val();
var description = $(‘#project-description’).val();
var company = $(‘#company’).val();
var addLocation = $(‘#include-location’).is(‘:checked’);

if (!name || !description || !company) {
alert(‘Please fill in all fields’);
return;
} else {
var result = self.storageService.addProject(
name, company, description, addLocation);

result.done(function() {
alert(‘Project successfully added’);
self.renderSearchView();
}).fail(function(error) {
alert(error);
});
}
},
renderSearchView: function() {
$(‘.tab-button’).removeClass(‘active’);
$(‘#search-tab-button’).addClass(‘active’);

var $tab = $(‘#tab-content’);
$tab.empty();

var $projectTemplate = null;
$(“#tab-content”).load(“./views/search-project-view.html”, function(data) {
$(‘#addressSearch’).on(‘click’, function() {
alert(‘Not implemented’);
});
$projectTemplate = $(‘.project’).remove();

var projects = self.storageService.getProjects().done(function(projects) {

for(var idx in projects) {
var $div = $projectTemplate.clone();
var project = projects[idx];

$div.find(‘.project-name’).text(project.name);
$div.find(‘.project-company’).text(project.company);
$div.find(‘.project-description’).text(project.description);
if (project.location) {
var url =
‘<a target=”_blank” href=”https://www.google.com.au/maps/preview/@’ +
project.location.latitude + ‘,’ + project.location.longitude + ‘,10z”>Click to open map</a>’;

$div.find(‘.project-location’).html(url);
} else {
$div.find(‘.project-location’).text(“Not specified”);
}

$tab.append($div);
}
}).fail(function(error) {
alert(error);
});
});
}

To add the console and therefore the dialog plugins, execute the following:

cordova plugin add org.apache.cordova.dialogs
cordova plugin add org.apache.cordova.console

The cordova.console plugin can assist you in debugging by enabling the console.log() perform inside emulators.

You can merely correct android applications through the Chrome remote debugger.

Once you’ve got connected your device, click the drop menu within the prime right corner (below the X button), expand a lot of Tools, also click on examine Devices. You must see your device within the list and may be ready to open its correct console.

Safari provides identical functionality for debugging iOS apps(development) that run on USB-connected device or imitator. Merely modify Developer Tools underneath the Safari Settings > Advanced tab.

The cordova.dialogs plugin allows native notifications. A standard applies to redefine the windows.

An alert methodology using the cordova.dialogs API within the following manner:

overrideBrowserAlert: function()
if (navigator.notification) { // Override default {html alert with native dialog
window.alert = function (message)
navigator.notification.alert(
message, // message
null, // {callback
“Toptal”, // title
‘OK’ // buttonName
);
};
}
}
The overrideBrowserAlert function ought to be referred to as within the deviceready event handler.

 

You should currently be ready to add new comes and consider existing ones from the database. If you choose the checkbox “Include location”, the device can create a call to the Geolocation API and add your current location to the project.

Let us add a finishing touch to the application by setting an icon and a splash screen. Add the after your config.xml file:
<platform name=”android”>
<icon src=”www/img/logo.png” />
<splash src=”www/img/logo.png” density=”mdpi”/>
<splash src=”www/img/logo.png” density=”hdpi”/>
<splash src=”www/img/logo.png” density=”xhdpi”/></platform>

Finally, place a logo image in the www/img folder.

We went through the fundamental steps of Apache Cordova cross platformapp development and also used our JavaScript architecture and CSS stylesheet.

This Cordova tutorial was an endeavor to indicate the potential of Apache Cordova as a method of developing mobile applications using acquainted technologies, reducing each development time and therefore the effort needed to create multiple forms for various platforms.

However, once building applications that may enter production, it’s recommended that you only use an existing framework.

Additionally, in structuring your application during a predefined design, therefore, additionally offer you a collection of elements which can facilitate your application return nearer to the native look and feel. Also, some frameworks worth noting are Ionic, Framework7, Weex, Ratchet, Kendo UI, and also Onsen UI.

If you like this blog?  stay tuned for more similar blogs 

Please follow and like us:
20

Ethan Root is an expert in Blogging, inbound marketing, content marketing, Digital Marketing and lead generation at TechTIQ Solutions [leading web development, mobile app development company in the UK]Connect with Ethan on Facebook and Linkedin

LEAVE A RESPONSE

Your e-mail address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial
Facebook30
Facebook
LinkedIn
Google+
https://www.techtiq.co.uk/blog/cross-platform-mobile-applications-cordova">