CHAPTER 3

image

Building Blocks of HMAD

Each mobile operating system has a considerably different architecture of its own. Each app running in an OS needs to communicate with device elements, such as the sensors and cameras. When you develop native applications targeting a specific OS or ecosystem, you have to understand how services are offered by that OS or ecosystem (in the form of APIs), to access device features like sensors and cameras.

However, when you develop hybrid applications, the first step is to choose the hybrid application framework and then understand how services are offered by the framework, in the form of APIs, to access device features like sensors. Hybrid application frameworks can communicate with device components. Since most hybrid application frameworks are based on the concept of browser-based sandbox applications, you need to understand how the browser engine works and its limitations.

This chapter presents the basics required for hybrid application development.

Architecture

Because you’re going to target mobile application development for three ecosystems—Android, Apple, and Microsoft—you first need to understand the building blocks of those operating systems. Then you’ll look at how hybrid applications can be ported on top of each OS. In this section, you’ll explore the differences between OS and browser runtimes.

OS Runtime

Each OS has a core component called a kernel. How is an API stack built on top of the kernel?

Let’s explore this for the three main ecosystems.

Android OS Layers

The Android OS was built by Google, based on the Linux kernel. Figure 3-1 depicts layers in the Android architecture with a Linux kernel at the base.

Any application built for Android natively will have to talk through an application framework layer. The code is run by the Android runtime and fed to it by a Dalvika virtual machine.

9781484213155_Fig03-01.jpg

Figure 3-1. Android layered architecture

While coding for native Android applications, you have to use libraries offered by the SDK itself. WebKit and SQLite are popular examples. If you are familiar with the process of how Java works, it’s mostly the same. A little extension to this understanding is required. Here are the details

Java

In a normal scenario, the developer has to code the application in Java. After compilation, the code gets converted into intermediate code called bytecode, instead of native code. Because of this, Java code can run on any platform; the code is not in native format, so it is yet to be converted into a CPU-specific format. After compilation, output is packaged and delivered as a JAR file. This is the end of development. When the JAR is delivered to the client, the code can’t run directly, as it is not in native format. A machine on which it runs needs installation of a Java Virtual Machine, which in turn offers a just-in-time interpreter. This can convert the code from bytecode form to native form. The JVM is platform dependent, which makes the Java platform independent. Figure 3-2 shows the Java execution procedure.

9781484213155_Fig03-02.jpg

Figure 3-2. Java execution

Now that you understand how to make Java code work on different platforms, here is how Android uses a Dalvik Virtual Machine to run bytecode.

Dalvik

Android applications are preferred to be coded in Java, due to the Dalvik Virtual Machine. The bytecode after compilation is translated for optimized performance and stored in the file format DEX/ODEX, also known as a Dalvik executable. Published under the Apache license, the Dalvik runtime was used by Google prior to the KitKat version of Android. Google included a new alternative runtime called Android Runtime (ART), in the KitKat version. ART replaced the Dalvik runtime entirely in the Lollipop version of Android. Figure 3-3 shows the Dalvik runtime.

9781484213155_Fig03-03.jpg

Figure 3-3. Dalvik runtime

So, this summarizes Android. Now let’s talk about iOS.

iOS Layers

Figure 3-4 depicts the layers in iOS.

9781484213155_Fig03-04.jpg

Figure 3-4. iOS layers

Each layer in this block diagram has features available, and to access or use those features, many frameworks are also available. Code written in Objective C or Swift does not directly talk with the underlying hardware. It has to talk through layers of the core OS in order get access to hardware. It is always recommended that you code at higher-level frameworks or libraries because there’s less complexity involved while dealing with the hardware.

Cocoa Touch Layer

The first layer is the Cocoa Touch layer. This helps you to define the appearance of the application while porting on the iOSplatform. Various sets of libraries (frameworks) available at this layer help the developer handle different gestures and do multitasking.

Here is a list of features in this layer:

  • App extensions
  • Handoff
  • Document picker
  • Air drop
  • Text kit
  • UI kit dynamics
  • Multitasking
  • Auto layout
  • Storyboards
  • UI state preservation
  • Apple push notification service
  • Local notifications
  • Gesture recognizers
  • Standard system view controllers

This is the first layer you should evaluate while creating iOS applications.

Some useful frameworks (set of libraries) available in this layer are as follows:

  • Address Book UI framework
  • Event Kit UI framework
  • Game Kit framework
  • iAd framework
  • Map Kit framework
  • Message UI framework
  • Notification Center framework
  • Push Kit framework
  • Twitter framework

Media Services Layer

This layer helps you use audio, video, and graphics in the application to implement a multimedia experience. Here is list of features in this layer:

  • Audio
  • Video
  • Graphics
  • Streaming

Some useful frameworks (set of libraries) available in this layer are as follows:

  • Assets Library framework
  • AV Foundation framework
  • AVKit framework
  • Core Audio framework
  • CoreAudioKit framework
  • Core Graphics framework
  • Core Image Framework
  • Core Text framework
  • Core Video framework
  • Game Controller framework
  • GLKit framework
  • Image I/O framework
  • Media Accessibility framework
  • Media Player framework
  • Metal framework
  • OpenAL framework
  • OpenGL ES framework
  • Photos framework
  • Photos UI framework
  • Quartz Core framework
  • SceneKit framework
  • SpriteKit framework

Core Services Layer

This layer helps you leverage cloud services, social media, and networking.

Here is a list of features in this layer:

  • Peer-to-peer services
  • iCloud storage
  • Block objects
  • Data protection
  • File-sharing support
  • Grand central dispatch
  • In-app purchase
  • Contents
  • SQLite
  • XML support
  • Audio
  • Video
  • Graphics
  • Streaming

Some useful frameworks (set of libraries) available in this layer are as follows:

  • Accounts framework
  • Address Book framework
  • Ad Support framework
  • CFNetwork framework
  • CloudKit framework
  • Core Data framework
  • Core Foundation framework
  • Core Location framework
  • Core Media framework
  • Core Motion framework
  • Core Telephony framework
  • EventKit framework
  • Foundation framework
  • HealthKit framework
  • HomeKit framework
  • JavaScript Core framework
  • Mobile Core Services framework
  • Multipeer Connectivity framework
  • NewsstandKit framework
  • PassKit framework
  • Quick Look framework
  • Safari Services framework
  • Social framework
  • StoreKit framework
  • System Configuration framework
  • WebKit framework

Core OS Layer

This layer contains the core APIs to help you deal with the underlying hardware. If you are using frameworks listed in these three layers, they are internally communicating with the underlying hardware through this Core OS layer. Very rarely do you need to use this layer.

Here is a list of features in this layer:

  • Security
  • Access to external hardware
  • Acting as a bridge between other layers and hardware
  • Some useful frameworks (set of libraries) available in this layer are as follows:
  • Accelerate framework
  • Core Bluetooth framework
  • External Accessory framework
  • Generic Security Services framework
  • Local Authentication framework
  • Network Extension framework
  • Security framework

So, this was about iOS. Now let’s talk about Windows Phone.

Windows Phone Layers

Windows Phone architecture has four main layers:

  • Hardware at the base
  • Windows NT kernel on top of it
  • App - UI model
  • Application framework at the top

Applications for Windows Phone are mainly developed in the Silverlight, XNA, HTML, and JavaScript frameworks. The majority of Windows Phone application development occurs with the Silverlight framework. XNA is used mainly for game development. HTML- and JavaScript-based native application development occurs less often than Silverlight.

To summarize, native mobile application development is through specific tools and languages, which always change with the platform. These applications always run closely with the operating system’s runtime.

Browser-Based Applications and Browser Runtime

To understand the browser runtime from the perspective of hybrid applications, you have to understand browser-based applications. You use a browser for requesting pages from web sites and viewing the same. Every browser understands web pages, whether static or dynamic, as every page finally gets converted into HTML only.

The browser is a program that internally has a layered architecture, as shown in Figure 3-5. To provide a common understanding among all browsers available, the World Wide Web Consortium (W3C) defined specifications for HTML. However, many browsers only partially follow the standard.

9781484213155_Fig03-05.jpg

Figure 3-5. Browser main layers

All browsers have key components such as the following:

  • User interface
  • Rendering component
  • Browser engine

The user interface represents the browser’s own look and feel, excluding the area where you can see the requested page. The rendering component involves an HTML parser, which, in turn, after parsing can generate the UI as well. The browser engine is the media between the user interface and the rendering engine.

Each browser, by default, understands HTML and CSS through the rendering engine. It also understands JavaScript code through a JavaScript interpreter.

The Problem with HTML

Older versions of HTML, before HTML5, have limitations in terms of what can be achieved. For example, playing a video using plain HTML tags or creating vector graphics was difficult.

Can we use desktop-based applications as they are in a web app? No and yes! No, we cannot, as the browser by default understands only an HTML UI, and desktop apps may not be HTML apps. Yes, we can use such applications, but plug-ins are needed to run them.

Due to such limitations, we never saw a new trend of browser-based applications such as Flash or Silverlight.

Flash

Adobe launched Flash (formerly called Macromedia Flash and Shockwave Flash) many moons ago, to create vector graphics, animation, browser games, rich internet applications, desktop applications, mobile applications, and mobile games. Flash would have survived only as a UI tool. However, understanding the needs of enterprises, Adobe also introduced Flex, which was equivalent to JSP/PHP, along with additional graphics-related functionality from Flash.

Silverlight

Microsoft launched Silverlight in 2007. It was equivalent to Flash, but offered more choices for coding. Since it was built on the .NET platform, every .NET web programmer could work in a language such as C# or VB.NET and create Silverlight applications. As for the UI, programmers had to learn XAML.

In Silverlight 3.0, Microsoft added a feature called Out of Browser. It allowed users to install the Silverlight application out of browser, on a desktop, with a single click. Users could find the application installed via a shortcut in the Programs menu. This feature bridged the gap between desktop and web-based applications, as Silverlight out-of-browser applications were safe and lightweight.

Microsoft also partnered with Novel to further extend Silverlight for open source, as Moonlight. Moonlight supported the out-of-browser application concept in the second version.

Flash and Silverlight—Good or Bad?

When these rich Internet applications got into the browser, they always worked in sandboxed mode, within the frame of the browser. Even when a Silverlight application is in out-of-browser mode, it always works in the browser’s sandbox, but without showing the browser window.

However, it was possible to acquire additional permissions from the user to get exclusive access to the user’s machine and file system. Whether it is Flash, Flex, or Silverlight, none of these types of applications would work on your machine (browser or mobile device) unless you installed the required plug-in or player to run it. For example, to run Flash on a user’s machine, Flash player installation is required. To run Silverlight, a player is required.

Flash, Flex, and Silverlight were never in compliance with the HTML standard. Usability experts always complained about them.

Many browsers don’t support installation of the plug-ins directly without user consent. This directly impacted the audience for these applications. The latest mobile devices contain more private data compared to desktops. Installing plug-ins can make users of such devices feel threatened. In addition, the Apple ecosystem bans the installation of plug-ins directly on the device. This means that a company developing web applications using Flash, Flex, or Silverlight loses a large set of the audience.

No one can say whether Flash and Silverlight were good or bad; they were a trend.

Image Note  Although Flash required installation of plug-ins on the user’s machine, almost 99 percent of Internet-enabled desktop machines have Flash installed (see www.adobe.com/devnet/Flashplayer/enterprise_deployment.html).

HTML5

Previous versions of HTML had limitations including cross-browser issues due to community-added tags and different ways of handling events by rendering engines. This was responsible for the trend of browser applications based on plug-ins.

Because some ecosystems ban plug-in installations, enterprises required another option. Hence we have HTML5.

HTML5 became a core markup technology standard for structuring and presenting content for the World Wide Web. The first draft of HTML5 was announced in 2009. The second and final draft was announced by W3C in 2014.

Figure 3-6 shows the evolution of this web standard.

9781484213155_Fig03-06.jpg

Figure 3-6. Web standards evolution

Enterprises gained the best of both trends: HTML and applications based on plug-ins for the Web. HTML5 offers the same by offering new tags and APIs in HTML. An API inside the HTML standard is a complete new offering! These APIs include location, offline storage, caching, and drag-and-drop.

Input controls became more powerful by offering built-in validation without using JavaScript.

The only problem with HTML5-based web applications is that they require browsers supporting HTML5. Figure 3-7 shows which API is supported on which browser.

9781484213155_Fig03-07.jpg

Figure 3-7. HTML5-supporting browsers

Again, because of these limitations, development of applications supporting multiple browsers becomes difficult. As for HTML5-specific features, you may have to write JavaScript code to emulate the same features on a nonsupporting browser, or you might lose a potential customer!

Over the Web, problems related to HTML5 support won’t exist if every browser vendor starts supporting equally, or end users upgrade their installed browsers to the latest versions supporting HTML 5. But since this is a new trend, why not leverage it?

HTML5 for All Development

Now that you understand that developing ecosystem-based mobile applications requires knowledge of a particular language and tool, web application development is trending toward HTML5.

Can you use HTML5 for installed mobile-based applications, as you can for web for desktop and mobile?

The answer is yes.

However, you have to consider certain obvious scenarios such as these:

  • How will HTML5-based mobile applications be installed on mobile devices?
  • Will these HTML5-based applications run under a browser context?
  • What language will you use to communicate with the server or database?
  • Will HTML5-based applications talk with underlying sensors?
  • Will it be compatible with different screen sizes?
  • And most important of all: Can HTML5-based applications target multiple ecosystems, as discussed previously?

To get an explanation for all of these, let’s explore hybrid applications and how they work.

How Hybrid Applications Work

If applications for mobile devices can be created with the help of HTML5, what can be used for writing logic (for example, for connectivity to the server and database communication) is JavaScript. JavaScript, as per ECMA standards, has been around for many years.

Figure 3-8 depicts a hybrid mobile application.

9781484213155_Fig03-08.jpg

Figure 3-8. A hybrid application

An HTML5 JavaScript-based web application can be extended to access device-specific features and packaged using frameworks such as PhoneGap, AppBuilder, and Ionic. These frameworks also help to package the same app for different ecosystems, as discussed previously.

Image Note  Most hybrid application frameworks are based on top of the Apache Cordova engine.

If you want to write common business logic for web and mobile devices as well, authoring business logic as a service by using service-oriented architecture (SOA) is suggested.

Apache Cordova

Apache Cordova, from the Apache Software Foundation (ASF), is an API using JavaScript to access device-specific features such as cameras and memory cards. These APIs can be combined with frameworks such as jQuery and Dojo. Using this combo, you can develop applications for mobile devices without using languages like Java, Objective C, or C# (see Figure 3-9).

9781484213155_Fig03-09.jpg

Figure 3-9. How Cordova works

Cordova provides JavaScript APIs, which in turn talk with Cordova’s native libraries. It can be used in combination with UI frameworks like jQuery along with AppBuilder and Ionic.

The most important thing is that Cordova is open source. More details about Apache Cordova can be found at http://cordova.apache.org.

Web Applications vs. Hybrid Mobile Applications

Because HTML and JavaScript-based hybrid mobile applications use the same UI as that of their web versions, there are chances of confusion between both. Table 3-1 helps put the differences in black-and-white.

Table 3-1. Web App vs. Hybrid Mobile App

Web Applications with HTML/CSS/JavaScript

Hybrid Mobile Applications with HTML/CSS/JavaScript

Using these applications requires browsing the UI via the browser and raising an HTTP request over the Internet.

Using these applications requires first installing the application on the mobile device. Depending on the nature of the application, you may or may not have to raise the request over the Internet.

JavaScript code written with these applications cannot communicate with the client hardware, as it is restricted to run within the browser premises.

JavaScript code written with these applications can communicate with the devices and the client hardware, with permissions, by using an engine like Apache Cordova.

The user interface can be heavy.

The user interface has to be lightweight, as the UI has less real estate in terms of screen size.

Both can use the same UI, but that UI has to have responsive design (see Figure 3-10). Responsive web sites automatically scale the application’s UI based on the device’s screen size. You will see more details about the responsive UI in Chapter 7.

9781484213155_Fig03-10.jpg

Figure 3-10. Responsive web design

Technologies, Frameworks, and Languages

Now let’s focus on the technologies, frameworks, languages, data formats, and packaging frameworks used in building hybrid mobile applications.

HTML5

As we discussed earlier in this chapter, HTML5 is a new web markup language standard, announced in 2009 by W3C. The second and final draft, originally scheduled for 2022, was published early in 2014. End users are required to install the latest browsers on their machines with the capacity of rendering HTML5 tags and APIs.

The number of users upgrading to the latest browsers supporting HTML5 has dramatically increased since the first draft launch. Because the plug-in approach is about to become out-of-date, the future of HTML5 in the web world looks bright!

Why HTML 5?

Most browsers supporting HTML5 are almost consistent in showing HTML5 tags and APIs. Those browsers that are partially incompatible with this standard are being neglected by end users.

Many of the cross-browser issues due to vendor-specific tags (for example, <icon>) also will be automatically solved if the entire web world is driven by the same markup standard.

There is no need to write JavaScript code for basic validations, because of the new input types available in HTML5. HTML5 supports new input types such as email, color, date, time, and number, which do validation as well (see Figure 3-11).

9781484213155_Fig03-11.jpg

Figure 3-11. New input elements in HTML5

For achieving functionalities such drag-and-drop and caching, you don’t need to code now. More APIs are built-in with HTML5.

Basics of HTML5 and Useful APIs

As discussed, HTML5 has new markup tags. It also makes many old tags and tag attributes obsolete because of nonusage or alternative availability. Let’s explore HTML5 basics and APIs.

To convey to the browser that the page is written with the HTML5 standard, the first tag is important. The line is as follows:

<!DOCTYPE html>

Following are the new structural tags in HTML5:

  • section presents generic content in group format.
  • article presents a self-contained composition.
  • aside presents complete tangent contents (for example, advertisements) compared to the rest of the page.
  • header represents a group of navigational aids.
  • footer presents normal footer content.

The following are the new content tags in HTML5:

  • figure presents flow content (which may be an image), with a caption preferred.
  • video shows video data; supported formats differ, based on the browser.
  • audio presents audio data; supported formats differ, based on the browser.
  • embed is used for hosting an external application.
  • canvas is used for rendering graphics.

The following are the new application-focused tags in HTML5:

  • meter presents a range or scale of values.
  • progress presents the amount of completion of a task.
  • time presents a 24-hour clock.
  • details is used for conveying additional information.

The following are deprecated in HTML5 due to replacement through CSS:

  • big
  • center
  • font
  • strike
  • U

The following are deprecated due to accessibility:

  • frame
  • frameset

HTML5 Detection

You can detect whether HTML5 is supported on a client-side browser in multiple ways; for example, you can use TAG with inline content. If the tag gets rendered, HTML5 is supported. If the content gets rendered, HTML5 is not supported.

<canvas style="height:100px, width:100px, background-color=yellow">
        HTML 5 is not supported
<canvas>

Using HTML5 specific APIs, you can check whether the API works; if it doesn’t work, you’ll see the respective message:

if(typeof(WebWorker) == 'object')
{
alert ('HTML 5 supported')
}
else
{
alert ('HTML 5 is not supported')
}

You also can use the Modernizr library to check whether HTML5 is supported. Modernizr is a JavaScript library that can be downloaded from https://modernizr.com/. This library helps detect programmatically any HTML5 features available on the browser.

HTML5-Specific APIs

In HTML5, APIs can be divided into two categories: integrated and associated.

Integrated APIs

Integrated APIs may not require any script code. These can be directly used, and be presented through TAG or file. Such APIs include Video, Audio, and Drag and Drop.

Video

The video tag does not require a third-party plug-in installation such as Flash:

<video src="<VIDEOFILE.EXTENSION>" width="100px" height= "100px" ><.video>

In the preceding example, VIDEOFILE.EXTENSION represents the pattern used to provide the source.

The following codec formats are recommended by vendors:

  • H.264 by Microsoft and Apple (conversion through the HandBrake utility)
  • OGG by Firefox and Opera (conversion through Firefogg on Firefox)
  • VP8 by Google and Mozilla (conversion through the HandBrake utility)

Audio

The Audio API is used for playing audio content over the browser, without a plug-in requirement. Supported formats include MP3 and WAV. This API can help the user browse content offered from the server side offline. You can convey to the browser what kind of resources need to be in cache at the client side.

The file used for specifying the cache part is standard, and is named cache.manifest. This file is required to be provided with the HTML tag itself, as follows:

<html manifest="cache.manifest">

The cache.manifest file is shown in Figure 3-12.

9781484213155_Fig03-12.jpg

Figure 3-12. Cache manifest’s sample cache file

This can surely improve the performance of the application from the client’s perspective.

Drag and Drop

This API enables you to drag one UI element and drop it at a particular container location. A few events (such as onDragEnter, onDragStart, and onDrop) need to be handled to achieve this action.

Associated APIs

Associated APIs require writing of the script code. Such APIs include Geolocation, 2D Canvas, Local Storage, Web Worker, and Web Sockets.

Geolocation

This API helps get the end user’s current location. The API is added as an extension to the navigator object and provides methods such as getCurrentPosition() and watchPosition(). To obtain the position of the end user, permission is required.

The reply from the API consists of latitude and longitude, which later can be integrated with the Google Maps or Bing Maps APIs.

2D Canvas

The Canvas API can be used to draw 2D graphics. Geometry elements such as a circle, rectangle, and line can be drawn with the help of the Canvas API. Canvas becomes a base for graph APIs in many application frameworks including the Sencha Touch framework.

You have to use a 2D context to get the x and y axes before drawing. There is no 3D context available as of now.

Local Storage

In normal cases, browsers support cookies (small text files storing a user’s profile data, such as login session ID or preferences). At a first visit, web servers and web sites may persist a cookie on the client machine to mark that the user has visited the server at that particular time. It may additionally store the user’s preferences. Upon the site being requested again, the cookie information can be packaged by the browser and sent to the web server or web site, which then can be used to identify the client or user’s preferences.

Although cookies are stored on the client’s machine, they are always used by the server when sent back by the browser.

HTML5 offers a Local Storage API by extending the traditional window object. You can use this API to store about 5MB of data in the key/value pair format on the client’s machine, based on the site’s domain. This content can be accessed using client-side JavaScript. If the server requires it, the data has to be sent back through client-side JavaScript! So, this is a client-side API to store data.

Web Worker

Client-side JavaScript is always a single-threaded environment; multiple scripts can’t run at the same time.

The Web Worker API in HTML5 brings threading to JavaScript. Now, you can run multiple scripts on the client side by using a web worker. You have to create a Web Worker object and assign a script to be executed as input in the form of a JS extension form.

Web Sockets

Over the Web, we use HTTP to communicate between a client browser and web server. HTTP is a stateless protocol; no continuous connection exists between the client and server. How will the server remember the client in the next trip? We use cookies and session concepts. Using these concepts, you can achieve stateful behavior.

The Web Socket API in HTML5 offers full, two-way (duplex) communication between the client and server. Underneath, it uses TCP. This becomes the base for web applications, which use video streaming or critical (or real-time), large data updates in the UI.

Data Formats

Whether you use HTML5 for web or hybrid mobile applications, communicating with the server is required for enterprise applications. If you consider hybrid mobile applications, then which format will you prefer to communicate with server? You have two industry standards available: XML and JSON.

Using XML

XML is a well-known standard defined by the W3C, way back in 1996. This standard became popular as many ecosystems launched APIs to support XML, including Microsoft, Apple, and Google.

After XML, browsers were launched along with an XML parser. Every browser supports an API for HTML as well as XML, called the Document Object Model (DOM), along with object support including Document, Window, and Navigator.

When JavaScript, as a client-side coding language, and DOM did not support XML natively, support was added externally by browser vendors including Microsoft, through the MSXML API.

Logic hosted on the web server and offered with the endpoints exposed is normally known as web services. Web services became the base for distributed enterprise applications. So, another thing that made XML more popular was web services.

Web services used XML over HTTP for communication, and were used as a middleware for cross-application platform communications such as Java and .NET.

XMLHttpRequest (XHR) was added in DOM version 2. Server-side support was built by many frameworks including Java server-side APIs and Microsoft .NET.

Drawbacks of XML

Though enterprises continue to use XML, it comes with one major drawback. Because XML data is always written in nodes, to those for whom only data matters, it seems to be carrying redundant parts.

Consider XML presenting an employee’s data:

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
        <Name> John </Name>
        <Id> 1928 </Id>
        <Age> 34 </Age>
        <Address>
                <City> Sydney </City>
                <Country> Australia </Country>
        </Address>
</Employee>

For someone who wants to know the data, knowing only that the John value stands for Name is sufficient. However, the XML syntax uses the end tag </Name>. Carrying this end tag as a set of characters makes the XML bulky. Using JSON format helps reduce the amount of data transfer.

Using JSON

JSON stands for JavaScript Object Notation The preceding XML about the employee can be presented in JSON as follows:

{ Name: 'John' , Id: '1928' , Age: 34 , Address: { City: 'Sydney' , Country: 'Australia' } }

As you can see, because you have no end tag as in XML, JSON format is shorter. Even complex data such as an address can be presented.

JSON format was formalized and made popular by Douglas Crockford. More details about the JSON data format can be seen at www.json.org.

Earlier there was no server-side support from popular frameworks like the Java server-side APIs and Microsoft .NET.

Over the Web, when a response is given by the web server, it always adds a content type. The default content type for response pages has always been text or html. As for XML, it was application or XML.

When JSON data used to arrive in client-side JavaScript, it was always taken as a string. Programmers used to get actual data by doing a string-split operation, until a helper file (json.js) was offered by Crockford.

DOM Version 2 Changes

Later native browser support was added for JSON in DOM version 2, along with an XHR object for XML. After DOM 2, JSON became a popular standard.

After the Android launch from Google, the smartphone market was shaken, with prices of the smartphone dramatically going down. Internet packs were made available by network providers at low rates. By then, smartphone users started browsing the Web over their mobile devices. Those web sites that used XML as a communication data format were noticeably slower than ones using JSON.

After this, using JSON in web applications became a trend.

Server-side support was added by many frameworks, including Java server-side APIs and Microsoft .NET. These APIs were used to convert framework-specific data formats into JSON, and also to understand the JSON passed from the client side.

Who Uses JSON?

Today web giants including Twitter, Microsoft, Facebook, and Google use JSON format for communication from server to client, and vice versa.

Reincarnation of JavaScript

Even mobile device versions of many web applications rely on JSON, because of the quickness and small amount of data transfer. Common issues with browsers include locating elements with specific classes, applying styles to multiple elements, and handling events in a cross-browser manner.

The tasks are possible in JavaScript but not easy to implement. Certain obstacles are guaranteed, including lack of expertise in JavaScript and lack of standard debugging practices.

The answer to all the problems discussed is jQuery!

jQuery

jQuery is a library based on JavaScript. It is written using JavaScript itself. Its code helps solve a major problem for a client script developer ( the cross-browser issue).

jQuery library code can be downloaded from www.jquery.com. The jQuery library comes in two flavors: a development version and a production version.

You can even download the library from Microsoft or the Google Content Delivery Network (CDN) by using these URLs:

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>

<script src=" https://ajax.googleapis.com/ajax/libs/jquery/jquery-1.9.0.js"></script>

jQuery provides several APIs to manipulate the DOM and handle events in a cross-browser way. It also heavily supports the JSON format. jQuery AJAX is comparatively easier than normal AJAX, with plain JavaScript.

jQuery Basics

Because jQuery is ultimately a library in JavaScript itself, if the client browser has restricted execution of JavaScript on the machine, even jQuery is restricted.

Like JavaScript, a jQuery library needs to be included in the script tag.

If you have to ask jQuery to search for an input text box with an ID such as txtName, then if you write the code as follows, the code simply fails. To use commands in jQuery, you have to use shorthand such as jquery or $. Of the two, use of $ is more commonly seen. Here, putting # before txtName means “find by ID.”

--------------------------------------------------------------------------------------
//.....................HTML ............................
//.....................HTML ............................
//.....................HTML ............................

<script language="text/javascript">

var resultName = jquery('#txtName').value(),                       //CODE FAILS HERE
alert(resultName),
</script>
//.....................HTML ............................
//.....................<txtName element> ......
//.....................HTML ............................
--------------------------------------------------------------------------------------

You would get an error conveying undefined element ‘txtName’! (Undefined what?)

This means that jQuery tried to find an element with the ID txtName, but could not find one even if you had it in HTML!

The problem is that you’re asking jQuery to execute the code way before the txtName control is loaded into the DOM hierarchy. So it cannot find it, because it tries before txtName is even created!

To ensure that the code gets called after the DOM tree and elements are loaded, you need to use the ready() function in jQuery as follows (replacing the preceding script block):

<script language="text/javascript">

        $(document).ready(SayHi),            //this will execute code in 'SayHi' function

        function SayHi()
        {
                var resultName = jquery('#txtName').value(),
                alert(resultName),
        }

</script>

jQuery prefers inline functions without names, which makes the jQuery syntax unique. The preceding script tag can be rewritten using jQuery’s preference as follows:

<script language="text/javascript">
        $(document).ready(function ()                         //function without a name!
        {
                var resultName = jquery('#txtName').value(),
                   alert(resultName),
        }),
</script>

jQuery Selectors

One of the unique selling points for jQuery are selectors, which allow page elements to be selected. To find an element in HTML, you can use a different selector technique, as you used # in the preceding example, which denotes selection by ID.

Selector syntax is as follows:

$(selectorExpression) or JQuery(selectorExpression)

The following basic selectors exist in jQuery:

  • To select nodes by tag name, use the tag name:

    $('div') selects all div elements

  • To select nodes by ID, use #:

    $('#mydiv') selects elements with the ID attribute set to mydiv

  • To select nodes by style class name, use .:

    $('.myStyle') selects all elements with CSS style class with the name myStyle applied

  • To select nodes by attribute value, use square brackets:

    $('input[type="text"]') selects all input elements with type = "text"

  • To select nodes by input nodes:

    $(':input') selects all input elements irrespective all their type

  • Miscellaneous:

    $('table:tr') selects all <tr> elements inside the <table> tag

    $('tr:even') selects all <tr> elements that are even numbers

Table 3-2 shows some of the most frequently used APIs.

Table 3-2. jQuery APIs

Function Name

Description

.val()

Returns the content assigned to the value attribute of a tag; for example, input.

.attr('attribute', 'val')

Works as a getter/setter for a particular attribute of an HTML tag.

.css(json)

Sets the values of attributes of a style property. The bulk are set in JSON format.

.html()

Gets the inner HTML value of container tags, such as div.

.filter(selector expression)

Works as the next-level filter to get a specific element in HTML.

.toggle()

Toggles between multiple classes applied on the HTML element.

.append() , .prepend()

Appends or prepends the content to a container. The selector is a container.

While working with hybrid mobile applications, you’ll be using a mobile-flavored plug-in on jQuery called jQuery Mobile. You will use more of jQuery in sessions to come!

Server-Side Support

Let’s focus on server-side support while working on hybrid mobile device applications (see Figure 3-13).

9781484213155_Fig03-13.jpg

Figure 3-13. Server-side support

HTTP Handlers

This is one of the oldest techniques for consuming input data, executing business logic, and returning the respective data. In Microsoft .NET, this technique is called an HTTP Handler. This is similar to a PHP page without UI elements but with business logic. Also, it is similar to a Java servlet without a UI.

The drawback to this approach is that if many functionalities need to be clubbed into a single handler, the handler becomes a God class, which is not a recommended practice.

Service-Oriented Architecture

According to W3C, service-oriented architecture (SOA) is “a set of components that can be invoked, and whose interface descriptions can be published and discovered.”

These components can be created and exposed with the help of frameworks such as Java server-side APIs, .NET, and PHP.

Web Services

Web services are web applications that do not produce HTML. They contain logic that accepts input in the form of XML over HTTP and reply in the same manner.

Based on who is going to call the logic or share the logic, and whether there are multiple clients, you can choose an SOA.

When you pick the web services approach, you first need to create a business component, which will be shared. This component can be called over HTTP. Data transfer happens strictly in XML.

This XML data transfer makes communication of web services with heterogeneous platforms like .NET and Java possible.

XML is transferred over an HTTP carrier. Technically, XML over HTTP along with a schema definition is referred to as SOAP (originally an acronym for Simple Object Access Protocol) .

Description of the service in the form of an XML document can be distributed so that clients can come to know about the methods or logic offered from the service itself.

Figure 3-14 shows the steps taken. The arrows in the figure convey whether the step is taken in the server or client context (or both).

9781484213155_Fig03-14.jpg

Figure 3-14. Service-oriented architecture

Even though it provided such a good service, the web services approach today is outdated.

When we have clients over the Web, putting logic as a web service serves the need. But when it comes to nonweb clients, web services lose out.

In 2006, Microsoft introduced another service-oriented approach, which is known as a unified communication platform or framework. The former code name for this was Indigo.

Windows Communication Foundation Service

Windows Communication Foundation (WCF) services have the following features:

  • Service oriented, just like web services
  • Multiple protocol support such as HTTP, TCP, .NET MSMQ, and P2P
  • Multiple data formats are supported
  • Built-in security APIs
  • Reliable messaging using MSMQ (Message Queuing)
  • DB transaction participation support

REST-Based Services

REST means Representational State Transfer. The main idea behind REST is that you should treat services as a resource. Also, you should be able to use HTTP to access those resources.

WCF with REST is an easy combination. REST offers end users the choice of XML or JSON.

Users can be exposed to all the CRUD (create, read, update, and delete) operations using WCF REST by decorating existing logic classes with attributes.

The REST-based format is also used by RSS/Atom feed reader tools.

Cascading Style Sheets (CSS) Version 3

You can use CSS to describe how an HTML element should look.

CSS has been around for many moons. Launching CSS3 along with HTML5, W3C offered the following additions to the existing CSS functionality:

  • Selectors, as in jQuery
  • New backgrounds and borders
  • New text effects
  • New 2D/3D transformations
  • Rounded corners
  • Multiple column layout

Responsive CSS

This feature of CSS will make the same web UI appear differently, depending on the user’s device size. If the application or web site is opened on a mobile device, tablet, or desktop browser, the UI will present as per the real estate in terms of screen size available.

Twitter Bootstrap

Twitter Bootstrap provides responsive CSS along with a 12-column grid layout.

Instead of specifying the size of the control, you can assign the class name to the HTML element offered by Bootstrap CSS. These class names help the element occupy a length as per 12-column grid. The available screen size is normally divided into 12 columns. Based on the size requirement, each element is offered 1–12 column-level classes.

Skeleton

Skeleton is also a responsive CSS library with a 12-column grid layout available. The Skeleton library is simpler to use than Bootstrap. There are fewer UI tools available that work with Skeleton compared to Bootstrap.

HMAD Development and Packaging Frameworks

What is a packaging framework? While creating HTML5 and JavaScript-based hybrid mobile applications, you can choose the base and packaging from a platter of frameworks. Packaging frameworks help you create a final deployable output based on the ecosystem. The frameworks listed here also help port the same code on multiple ecosystems.

All these frameworks enable applications to compile on top of the Apache Cordova engine. Applications built on platforms are always going to run in web view.

This section describes some of the frameworks that are frequently used.

Ionic

This open source framework focuses on creating good applications in terms of patterns and practices. Ionic uses the AngularJS library for code purposes. It also recommends code in a Model-View-View Model (MVVM) design format, while presenting the browser (client) side alone.

Three layers exist in the MVVM design pattern, as shown in Figure 3-15:

  • Model: JSON or XML data objects that may be received from the server
  • View: HTML UI or CSS
  • View Model: JavaScript code that can bind JSON or XML data (the model) with the UI (the view)

9781484213155_Fig03-15.jpg

Figure 3-15. How MVC layers talk with each other

Applications created with Ionic include the following:

  • ChefSteps: Cooking application
  • Mallzee: Personal styling application
  • Sworkit: Body and fitness application

More information about Ionic can be found at http://ionicframework.com/.

PhoneGap

Compared to any other framework listed here, PhoneGap is more of packaging framework. You can choose a JavaScript library for code like jQuery, plain JS, and AngularJS. After coding is done, PhoneGap can package the same, based on the need. PhoneGap is owned by Adobe and is based on top of the Apache Cordova engine discussed earlier in this chapter.

PhoneGap supports compilation in the cloud (using Software as a Service) without installing the SDK required for packaging applications based on ecosystems.

Some of the applications created with PhoneGap are as follows:

  • snowbuddy: More of personal assistant or buddy type application
  • indoona: Chatting application
  • jigsaw: A jigsaw game application

More information about PhoneGap can be found at http://phonegap.com/.

AppBuilder

This product from Telerik was formerly called Icenium. AppBuilder has many similarities with PhoneGap, including having Apache Cordova at its base.

AppBuilder extends compilation-in-the-cloud functionality (just like PhoneGap) to offer code with tools such as these:

  • Command-line interface (CLI)
  • In-browser client
  • Windows-based desktop application

It also offers a plug-in to popular IDEs such as Visual Studio and Sublime Text.

The following are some of the applications created with AppBuilder:

  • Survey Data Plus Plus: Survey automation software
  • Birthplace: Healthcare application

More information about AppBuilder can be found at www.telerik.com/appbuilder.

Kendo UI

Kendo UI is another professional framework from Telerik, but with the advantage of lots of rich UI widgets. Kendo UI has more than 70 UI widgets and more than a dozen built-in UI themes. It supports AngularJS and Bootstrap.

Some of the applications created with Kendo UI are as follows:

  • Udemy: Education-related application
  • LunchBoat: Social meal planning application

More information about Kendo UI can be found at: www.telerik.com/kendo-ui/.

Angular UI

Mobile Angular UI is just like Sencha Touch. An important fact to note is that it has tailor-made Bootstrap. Bootstrap does not directly offer sidebars or bottom navigation bars. Mobile Angular UI helps you get all of that along with Bootstrap! Mobile Angular UI is free and open source.

More information about Mobile Angular UI can be found at http://mobileangularui.com/.

Sencha Touch

One of the best framework platforms for building hybrid applications is Sencha Touch. Sencha Touch is a paid framework, which comes with more than 50 UI components often required in enterprise applications.

Sencha is fast in execution. It uses a Model-View-Controller (MVC) design pattern, considering code at the browser/client side.

It recommends using Ext JS, a JavaScript library.

The following are applications created with Sencha Touch:

  • TravelMate: Travel domain application
  • Xero: Mobile-based accounting application
  • Tubetweet: A chatting and tweeting application

More information about Sencha Touch can be found at www.sencha.com/products/touch/.

Intel XDK

The XDK framework from Intel comes with an end-to-end development studio for mobile application developers. It consists of almost everything required for hybrid development including IDE, debugger, emulators, and deployment helpers. Code is supported using HTML5 and JavaScript.

Some of the applications created with Intel XDK are as follows:

  • Home Remedies: Helper-in-life kind of application
  • Press and Hard: A puzzle game application

More information about Intel XDK can be found at https://software.intel.com/en-us/intel-xdk/.

Testing Mobile Applications

Hybrid mobile application testers and developers may test applications for functionality, usability, and consistency.

Testing with Browsers

If an application is created with HTML and JavaScript, that application can be tested for functionality on a browser. The Chrome, IE, and Firefox browsers provide developer tools to debug and simulate certain behaviors.

The key challenge in this type of application testing is that the market has many devices with different screen sizes, operating systems, and so forth. How can you test applications for different mobile device sizes?

The answer is shown in Figure 3-16.

9781484213155_Fig03-16.jpg

Figure 3-16. Responsive web design over the Internet

A developer who is running the application can use www.responsinator.com, to test the UI by using simulation.

Although working with a browser while testing has its advantages, you can’t test device features such as an SD card or camera, because these features will be available only on mobile devices.

Hybrid applications can access device features when run in a web view; this means that though these applications are running in a browser context, they will always be running with elevated permissions.

So, you need to install applications on devices in order to test them.

Testing on Devices

If you need to test hybrid applications on iOS, Windows, or Android devices, each platform vendor will have different rules. Apple and Microsoft demand that you register for an Apple or Microsoft developer account.

Chapter 1 provides details on registration. Android may allow you direct installation by circulating the output file.

Therefore, testing applications for multiple devices is costly.

Testing with Packaging Frameworks

While developing application IDEs such as Visual Studio, Intel XDK may help developers and testers to debug or test applications. For an AppBuilder-like framework, you may get an extension to an IDE like Visual Studio.

These IDEs also come with emulators that help test the program on the dev machine itself.

After the testing phase is over, deployment of the application is planned.

Deploying Applications

Distributing an application in the Android ecosystem can be done freely and easily. If you want the app to be uploaded on Google Play, you must have a developer account.

When it comes to Apple and Microsoft, you are required to have a developer license. This allows one developer to test a specified number of applications on a single device.

If the application hosted is a paid one, then Apple, Microsoft, or Google takes a share in the minimum amount of money that you earn. Typically, the share ratio is 70:30.

Considering Cost

If your client wants an application to be put on iOS, Windows Phone, and Android devices, this native app development will be expensive in terms of money and effort because of the various compliance restrictions.

But when you decide to go hybrid, you have the following benefits:

  • Less cost
  • One code base
  • Responsive code that helps build the UI for each type of device
  • Less development time

Summary

This chapter covered the building blocks of hybrid mobile application development (HMAD). In the next chapter, you will create your first hybrid application by using Telerik AppBuilder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.68