Build hybrid mobile apps with Apache Cordova

Build hybrid mobile apps with Apache Cordova

[[127393]]

【51CTO translation】 You have finished building the front end for your application, and it also has mobile support. Now you want to provide native client applications that users can download from the app store. After reading this tutorial, you will understand how to reuse existing HTML5 code and use Apache Cordova to develop native mobile client programs for each target platform.

You will learn how to:

• Modify the existing web application so that the application can be deployed as a hybrid mobile application.

• Develop native apps for Android and iOS with Apache Cordova.

What is a Hybrid Mobile App?

Hybrid mobile apps are developed in HTML5 - unlike native apps which are compiled into binary code for a specific platform. The client-side code consists entirely of HTML, CSS and JavaScript, which is packaged and installed on the client device exactly like any native app, and then executed within a browser process spawned by the surrounding native shell.

In addition to encapsulating the browser process, the native shell also allows access to native device features such as the accelerometer, GPS, contact list, etc., which the application can use through JavaScript libraries.

In this example, we use Apache Cordova to deploy a hybrid application that uses TicketMonster's existing HTML5 mobile front end and interacts with Representational State Transfer Protocol (REST) ​​services from a TicketMonster deployment running on JBoss A7 or JBoss Enterprise Application Platform (EAP).

Figure 1: Hybrid TicketMonster architecture

Modifying the application for remote access

Before we make our application a hybrid application, we need to make some changes to the way our application accesses remote services. Please note: these changes have already been implemented on the user frontend, and we show you the code that needs to be changed here.

In the web version of the application, the client-side code is deployed alongside the server-side code, so that models and collections (and any part of the code that will perform REST service calls) can use URLs relative to the application root: all resources are served by the same server, so the browser will make the correct calls. This also respects the same-origin policy that browsers enforce by default to prevent cross-site scripting attacks.

If the client code is deployed separately from the service, REST calls must use absolute URLs (we'll explore the impact of this on the same-origin policy later). Also, since we want to be able to deploy the application to different hosts without rebuilding the source code, it must be configurable.

You already got an overview of this in the User Frontend chapter, where we defined the configuration module for the mobile application.

  1. src/main/webapp/resources/js/configurations/mobile.js
  2. ...
  3. define( "configuration" , function() {
  4. if (window.TicketMonster != undefined && TicketMonster.config != undefined) {
  5. return {
  6. baseUrl: TicketMonster.config.baseRESTUrl
  7. };
  8. } else {
  9. return {
  10. baseUrl: ""   
  11. };
  12. }
  13. });
  14. ...

The module has a baseURL property that can be set to either an empty string for relative URLs or a prefix, such as a domain name, depending on whether a global variable named TicketMonster has already been defined, which has a baseRESTUrl property.

All of our code that performs REST service calls depends on this module, so the base REST URL can be configured in a single place and injected throughout the code, as shown in the following code example:

  1. src/main/webapp/resources/js/app/models/event.js
  2. /**
  3. * Event model module
  4. */  
  5. define([
  6. 'configuration' ,
  7. 'backbone'  
  8. ], function (config) {
  9. /**
  10. * Event module class definition
  11. * Used to perform CRUD (create, read, update, delete) operations on a single event
  12. */  
  13. var Event = Backbone.Model.extend({
  14. urlRoot: config.baseUrl + 'rest/events'   // the URL for performing CRUD operations  
  15. });
  16. // Output event class  
  17. return Event;
  18. });

All other modules that perform REST service calls use the prefix in a similar manner. You don't have to do anything right now, as the code we wrote in the User Frontend tutorial was originally written this way. Be careful though, if you have a mobile web application that uses any relative URLs, you will need to refactor them to incorporate some kind of URL configuration.

#p#

Installing Hybrid Mobile Tools and CordovaSim

Hybrid Mobile Tools and CordovaSim are not installed as part of JBoss Developer Studio. They can be installed from JBoss Central as follows:

1. To install these plugins, simply drag the following link to JBoss Central: https://devstudio.jboss.com/central/install?connectors=org.jboss.tools.aerogear.hybrid. Alternatively, in JBoss Central, select the Software/Update tab. In the Find field, type JBoss Hybrid Mobile Tools, or scroll through the list to find JBoss Hybrid Mobile Tools + CordovaSim. Select the corresponding checkbox and click Install.

Figure 2: Click the link to start the installation process of Hybrid Mobile Tools and CordovaSim.

Figure 3: Hybrid Mobile Tools and CordovaSim are found in the Software/Updates tab of JBoss Central.

In the installation wizard, make sure the check boxes are selected for the software you want to install and click Next. It is recommended that you install all selected components.

Carefully review the details of the items listed for installation and click Next. After reading and agreeing to the license, click I accept the terms of the license agreement(s) and click Finish. The Installing Software window will open, reporting the progress of the installation.

During the installation process, you may receive a warning that unsigned content is being installed. If so, read the content details carefully, and if you are satisfied with the content, click OK to continue the installation.

Figure 4: Warning indicating that the installed software contains unsigned content.

Once the installation is complete, you will be prompted to restart the IDE. Click Yes to restart immediately, or click No if you need to save any unsaved changes to the open projects. Note: The changes will not take effect until the IDE is restarted.

Once installed, you must tell Hybrid Mobile Tool the location of the Android SDK before you can use Hybrid Mobile Tool actions involving Android.

To set the location of the Android SDK, click Window → Preferences and select Hybrid Mobile. In the Android SDK Directory field, type the path to the installed SDK, or click Browse and browse to the location. Click Apply and then click OK to close the Preferences window.

Figure 5: The Hybrid Mobile panel of the Preferences window

#p#

Developing hybrid mobility projects

1. To develop a new hybrid mobile project, click File → New → Other and select “Hybrid Mobile (Cordova) Application Project”.

Figure 6: Starting development of a new hybrid mobile application project

2. Enter the project information: Application Name, Project Name, and Package.

Project Name

TicketMonster - Cordova

name

TicketMonster - Cordova

ID

org.jboss.jdf.example.ticketmonster.cordova

Figure 7: Developing a new hybrid mobile application project

Click Next and select the Hybrid Mobile Engine for the project. If you have never installed the Hybrid Mobile Engine before in JBoss Developer Studio, you will be prompted to download or search for an engine that you can use. We will click the Download button to perform the former action.

Figure 8: First installation of the hybrid mobile engine

You will be prompted with a dialog box where you can download all available hybrid mobile engines.

Figure 9: Select the Hybrid Mobile Engine to download

We will choose version 3.4.0 for both Android and iOS variants.

Figure 10: Select Android and iOS for 3.4.0

Now that we have downloaded and installed the Hybrid Mobile Engine, let's use it in our project. Select the engine we just configured and click Finish.

Figure 11: Developing a new hybrid mobile application project

Once you have completed the development of the project, navigate to the www directory, which contains the HTML5 code for the application. Since we are reusing the TicketMonster code, you can simply replace the www directory with a symbolic link to the TicketMonster webapp directory; the config.xml file and the rest directory need to be copied over to the TicketMonster webapp directory. Alternatively, you can clone the TicketMonster code and make all the necessary changes there (though in that case, you will need to maintain the application code in both places.)

  1. $ cp config.xml $TICKET_MONSTER_HOME/demo/src/main/webapp
  2.  
  3. $ cp res $TICKET_MONSTER_HOME/demo/src/main/webapp
  4.  
  5. $ cd ..
  6.  
  7. $ rm -rf www
  8.  
  9. $ ln -s $TICKET_MONSTER_HOME/demo/src/main/webapp www

Figure 12: Result of linking www to webapp directory

The Hybrid Mobile Tool requires that the cordova.js file be loaded into the application's start page. Since we don't want to load that file into the existing index.html file, we'll create a new start page that only Cordova applications can use.

  1. src/main/webapp/mobileapp.html
  2. <!DOCTYPE html >  
  3. < html >  
  4. < head >  
  5. < title > Ticket Monster </ title >  
  6. < meta   http-equiv = "Content-Type"   content = "text/html; charset=utf-8" />  
  7. < meta   name = "viewport"   content = "width=device-width, initial-scale=1, user-scalable=no" />  
  8. < script   type = "text/javascript"   src = "resources/js/libs/modernizr-2.6.2.min.js" > </ script >  
  9. < script   type = "text/javascript"   src = "resources/js/libs/require.js"  
  10. data-main = "resources/js/configurations/loader" > </ script >  
  11. </ head >  
  12. < body >  
  13. </ body >  
  14. </ html >  

Now let's modify the hybrid mobile project's configuration to use this page as the application's start page. In addition, we'll add our REST service URL to the domain whitelist in the config.xml file (for simplicity, you can also use "*" during development):

  1. src/main/webapp/config.xml
  2. <? xml   version = "1.0"   encoding = "utf-8" ?>  
  3. < widget   xmlns = "http://www.w3.org/ns/widgets"   xmlns:gap = "http://phonegap.com/ns/1.0"  
  4. id = "org.jboss.jdf.example.ticketmonster.cordova"   version = "2.0.0" >  
  5. ...
  6. <!-- The application start page -->  
  7. < content   src = "mobileapp.html"   />  
  8. <!--
  9. Add the TicketMonster cloud app to the domain whitelist.
  10. Domains are assumed blocked unless set otherwise.
  11. -- >  
  12. < access   origin = "http://ticketmonster-jdf.rhcloud.com" />  
  13. ...
  14. </ widget >  

Next, we need to load the library into the application. We will also build a separate module. In addition to loading the Apache Cordova JavaScript library for Android, this module will also load the rest of the mobile application. We also need to configure the base URL of the application. For this example, we will use the URL of TicketMonster deployed in the cloud.

  1. src/main/webapp/resources/js/configurations/hybrid.js
  2. // Override config for services that take full advantage of REST  
  3. var TicketMonster = {
  4. config:{
  5. baseRESTUrl: "http://ticketmonster-jdf.rhcloud.com/"  
  6. }
  7. };
  8. require([ '../../../cordova' ], function() {
  9. var bootstrap = {
  10. initialize: function() {
  11. document.addEventListener( 'deviceready' , this .onDeviceReady, false );
  12. },
  13. onDeviceReady: function() {
  14. // Check if it is iOS 7 or higher, and disable overlaying the status bar  
  15. if (window.device.platform.toLowerCase() == "ios" &&
  16. parseFloat(window.device.version) >= 7.0 ) {
  17. StatusBar.overlaysWebView( false );
  18. StatusBar.styleDefault();
  19. StatusBar.backgroundColorByHexString( "#e9e9e9" );
  20. }
  21. // Load the mobile module  
  22. require ([ "mobile" ]);
  23. }
  24. };
  25. bootstrap.initialize();
  26. });

Note: We will be using the OpenShift hosted version of the TicketMonster application because it is easier to access in all environments - smartphone simulators and emulators can access it with little configuration. On the other hand, accessing a locally running JBoss EAP instance can require some complex network configuration; opening the instance to the internet so it can be accessed from a smartphone is even more complex.

The above code snippet contains the device-specific checks for iOS 7. We will use the Cordova Status Bar plugin to ensure that the status bar on iOS 7 does not overlap the UI. The Cordova Device plugin will be used to get the device information used when detecting the device. We will also use the Cordova Notification plugin to display alerts and notifications to the end user using the native mobile UI.

We will proceed by adding the required Cordova plugins to the project.

Select the plugins directory of the hybrid mobile project and open the context menu by right-clicking your mouse. Select the Install Cordova Plug-in option from the menu. This will open a dialog where you can search for Cordova plugins in various locations, including the Cordova registry, git repositories, or directories in your file system.

Figure 13: Launching the Cordova plugin discovery wizard

Now we will search for and add the required plugins:

Figure 14: Adding the Cordova device plugin

Figure 15: Adding the Cordova Notification plugin

Figure 16: Adding the Cordova status bar plugin

Click the Next button to verify the version of the plugin to be installed. Click the Finish button to download the plugin and install it into the project.

Figure 17: Verify the plugin to be added

The last step requires adjusting src/main/webapp/resources/js/configurations/loader.js to load the module when running on Android, using the query string we have configured in the project. We will also adjust src/main/webapp/resources/js/app/utilities.js to use the notification plugin to display alerts in the context of the hybrid mobile application.

  1. src/main/webapp/resources/js/configurations/loader.js
  2. // Detect the appropriate module to load  
  3. define( function () {
  4. /*
  5. A simple check for the client. If it is a touch device or a low resolution screen,
  6. Display mobile client. By enabling mobile client on low resolution screens,
  7. We allow testing outside of the mobile device (such as JBoss Tools and
  8. Mobile browser emulator in JBoss Developer Studio).
  9. */  
  10. var environment;
  11. if (document.URL.indexOf( "mobileapp.html" ) > -1) {
  12. environment = "hybrid" ;
  13. }
  14. else   if (Modernizr.touch || Modernizr.mq( "only all and (max-width: 768px)" )) {
  15. environment = "mobile" ;
  16. } else {
  17. environment = "desktop" ;
  18. }
  19. require([environment]);
  20. });

Now we'll take a closer look at the displayAlert function in the utilities object. It is set up to use the notification plugin if one is available:

  1. src/main/webapp/resources/js/app/utilities.js
  2. ...
  3. // Utility function to display the template  
  4. var utilities = {
  5. ...
  6. applyTemplate: function (target, template, data) {
  7. return target.empty().append( this .renderTemplate(template, data));
  8. },
  9. displayAlert: function (msg) {
  10. if (navigator.notification) {
  11. navigator.notification.alert(msg);
  12. } else {
  13. alert(msg);
  14. }
  15. }
  16. };
  17. ...

This function automatically works in non-mobile environments due to the lack of navigator.notification objects in such environments.

#p#

Running hybrid mobile applications

Now you are ready to run the application. Hybrid Mobile applications can be run on devices and emulators using the Hybrid Mobile Tools.

Run on an Android device or emulator

Notice:

What do you need to do for Android?

To run on an Android device or emulator, you need to install the Android Developer Tools, which requires an Eclipse instance (JBoss Developer Studio can be used), and can be run on Windows (XP, Vista, and 7), Mac OS X (10.5.8 or later), Linux (GNU C Library - glibc 2.7 or later, 64-bit distributions with the necessary libraries installed to run 32-bit applications).

You must have Android API 17 or later installed on your system to use the Run on Android Emulator action.

To run the project on a device, right-click the project name in the Project Explorer view and click Run As → Run on Android Device. This option calls the external Android SDK to wrap the workspace project and run it on an Android device if one is connected. Note: the Android SDK must be installed and the IDE must be properly configured to use the Android SDK for this option to succeed.

To run the project on the emulator, in the Project Explorer view, right-click the project name and click Run As → Run on Android Emulator.

Figure 18: Running the application on the Android emulator

This requires you to build an Android AVD (Android Virtual Device) in order to run your application in a virtual device.

Once deployed, the application can now be used interactively in the simulator.

Figure 19: Application running on Android AVD

Running on iOS Simulator

Notice:

What do you need to do for iOS?

This option only appears if you are using OS X, which has an iOS simulator. You must have Xcode 4.5+ installed, which includes the iOS 6 SDK. You will also need to install the simulator for iOS 5.x or later in order to run your project on the simulator. You may need a later version of the simulator to run your app, depending on the various Cordova plugins you may be using.

In the Project Explorer view, right-click the project name and click Run As → Run on iOS Emulator.

Figure 20: Running the application on the iOS simulator

This option calls the external iOS SDK, wraps the workspace project into an XCode project, and then runs it on the iOS simulator.

Figure 21: Application running on iOS Simulator

Running on CordovaSim

CordovaSim lets you run hybrid mobile apps in your local workspace. You can develop apps and implement their behavior without deploying to actual devices, or even to emulators and simulators. You have some limitations on what you can do with CordovaSim; for example, some Cordova plugins may not be compatible with CordovaSim. But overall, what you get is a faster development cycle.

In the Project Explorer view, right-click the project name and click Run As → Run with CordovaSim. This opens the application in CordovaSim, which consists of the BrowserSim simulated device and the Device Input Panel.

Figure 22: Application running on CordovaSim

Conclusion

This tutorial walks through the process of building a hybrid application with Apache Cordova. You may have seen how we took a working HTML5 web application and turned it into an application that can run directly on Android and iOS.

Original English text: Creating hybrid mobile versions of the application with Apache Cordova

Translated by Bugatti. Please indicate the translator and the original source of the translation when reprinting.

<<:  W3C CEO visits China and discusses HTML5 development in Asia Pacific

>>:  51CTO interviews Wang Tao, CTO of Sequoia Database: Methods of data processing and technology selection in the era of big data

Recommend

New Channel for App Store Promotion: Mobile Video Advertising

As App promotion channels mature, CPs and publish...

The most complete! Summary of mini program channel promotion, saved!

Mini Program is a lightweight product that was no...

How Amazon ignited the robot arms race

Workplaces at Amazon warehouses are often hectic ...

World Bipolar Disorder Day丨They are neither geniuses nor crazy...

Today, March 30, is World Bipolar Disorder Day. M...

4 Misconceptions of APP Acquisition of Users, Have You Fallen into Them?

Regardless of whether users are easy to dig, avoi...

What is a suitable gift for teachers on Teacher's Day?

The annual Teachers' Day is here again. I saw...

5 golden rules for designing mobile emails

Email design on mobile devices involves more than...

Five major mobile application development trends, is your app going astray?

Developers cannot ignore mobile app development i...