MQTT with mobile platforms
The number of different types of devices that can benefit from MQTT implementations is growing everyday. This chapter provides information about the available technologies to develop MQTT mobile applications.
This chapter describes how to develop a hybrid mobile application using IBM Worklight Studio for the Android platform. It contains an example application to show you how to send requests, receive responses, and push notifications on wanted quality of service (QoS) using MQTT.
This chapter includes the following topics:
5.1 Mobile application development considerations
Mobile communication devices are the fastest growing application segment. The traditional mobile phone has evolved into a powerful computing device, and new platforms and mobile operating systems are also now available.
Despite the wide variety of available technological capabilities, architects and developers must recognize the following factors when considering building applications for mobile devices:
Preservation of battery life
Mobile communication devices are designed, as the name implies, to be mobile. Therefore, as a general rule, the time interval between charges must be as long as possible.
Independent of the device’s platform or battery technology, running applications use resources (processor, memory, and network connectivity) and use battery power. Even when application management is generally
a platform’s choice, design applications to use the fewest resources possible.
Processing capacity
Even when mobile devices have a relatively good processing capacity, make applications as simple as possible in terms of processing, to speed up response time and to help preserve battery life.
Network optimization
Mobile devices must have at least one network connectivity option. In fact, most devices have a choice between several connection possibilities that vary in speed, connectivity range, battery consumption, and cost to the user. As a general rule, most types of connectivity are at some point limited in range.
Mobile applications can switch between available communication options seamlessly, based on a set of user-defined preferences. By doing this, an application can use a pre-configured IEEE 802.11x (WiFi) connection when available, and then switch to a 3G or 4G cellular connection when the WiFi is out of range. Design the application to continue its functionality in a transparent manner.
Platform capabilities
Base requirements to build applications can vary from one platform to another. Usually, the platform owner provides a set of application programming interfaces (APIs) to develop applications for their platform. Sometimes, as with MQTT, freely available implementations of the protocol allow the developer to concentrate on the application functionality, and use the MQTT protocol as a service.
5.2 Mobile application development models
Several approaches for developing mobile applications exist. Figure 5-1 illustrates the capabilities of the four most important approaches.
Figure 5-1 Mobile application development models
Mobile applications can be developed using any of the four different approaches:
Web applications
They are written entirely in HTML5, Cascading Style Sheets (CSS), and JavaScript code. Web applications are run by the mobile browser, and are cross-platform by default.
Hybrid applications (web)
The source code of the application consists of web code run within a native container, and consists of native libraries.
Hybrid applications (mixed)
The developer augments the web code with native language to create unique features, and access native APIs that are not available in JavaScript.
Native applications
This type of application is platform-specific, and requires expertise and knowledge of the platform.
5.2.1 Web application (browser access) development
If you use the web application development approach, your mobile application runs inside the browser of the mobile device, and uses standard technologies, such as HTML5, CSS3, and JavaScript. Mobile web applications are platform-independent, and no redevelopment is required to support a new mobile platform. However, modifications in the application might be required to support a different browser engine.
Mobile web applications cannot access the platform functions, because they rely only on the browser and the associated web standards. Mobile web applications are not distributed through an application store. They are accessed through a link on a website, or a bookmark in the mobile browser of the user.
Figure 5-2 illustrates an example of a web application (http://m.ibm.com/us/en/) opened through a Google Chrome browser.
Figure 5-2 Example of a web application
5.2.2 Hybrid application (web) development
Mobile applications implemented with the hybrid development approach use parts of both the native development and web development approaches. Mobile hybrid applications run inside a native container, and uses the browser engine to display the application interface, which is based on HTML and JavaScript.
With the native container, your mobile application can access device capabilities that are not accessible to web applications, such as the accelerometer, camera, and local storage on a smartphone. Similar to native applications, hybrid applications are distributed through the platform application store.
5.2.3 Hybrid application (mixed) development
Mobile applications developed using the hybrid mixed development approach use a container to access device capabilities, but also use other native, platform-specific components, such as libraries or specific user-interface elements, to enhance the mobile application.
5.2.4 Native development
Mobile applications developed using the native development approach are developed for a specific platform, and run on that platform only. These mobile applications can fully use all of the platform functions, such as accessing the camera or contact list, or interacting with other applications on the device.
To support different platforms, such as Android, iOS, BlackBerry, and Windows Phone, application developers must develop separate applications with different programming languages, such as Objective-C for iOS, or Java for Android. Typically, native applications are distributed through an application store.
5.2.5 Comparing the different approaches
Each of these development approaches has advantages and disadvantages. The specific requirements for an individual mobile solution drive the selection of an appropriate development approach.
In addition to the design and development of mobile applications, other topics are important also. Depending on the architecture of the application, running certain parts of the business logic as back-end services might be possible. These might have to be developed from the beginning (“from scratch”), but existing services typically can be used or adapted.
These services must be integrated into the mobile solution, and developing all of these components to create the solution involves various skills, not just mobile application development. Table 5-1 provides a comparison of different development approaches.
Table 5-1 Development approaches
Feature
Native application
Hybrid application
Web application
Development language
Native only
Native and web or web only
Web only
Code portability and optimization
None
High
High
Access device-specific features
High
Medium
Low
Use existing knowledge
Low
High
High
Advanced graphics
High
Medium
Medium
Upgrade flexibility
Low
(Always by way of application store)
Medium
(Usually by way of application store)
High
Installation experience
High
(from application store)
High
(from application store)
Medium
(by way of mobile browser)
Another challenge in developing mobile applications is testing. If the application is intended for multiple platforms, it must be tested on all of them. For each platform, developers might have to test different devices with different functionality and display sizes.
In addition, to run end-to-end tests, the devices must have access to a test environment. This poses a problem, because in traditional web development, a test environment is usually protected behind firewalls and not connected to the Internet.
5.3 IBM Worklight
IBM Worklight is a mobile application platform containing all of the tools required to develop a mobile application, including implementation, testing, and distribution. IBM Worklight facilitates the creation and delivery of rich, secure mobile applications. It simplifies end-to-end security and service integration between mobile applications and back-end systems.
It makes cross-platform application development easier through the use of standards-based technologies, such as HTML5 or JavaScript, and tools that can access native device capabilities. IBM Worklight consists of five core components, as illustrated in Figure 5-3.
Figure 5-3 Five components of IBM Worklight
Each component provides a specific set of functions and supports a different stage in the lifecycle of a mobile application:
Worklight Studio An Eclipse-based development environment with a rich set of tools for developing cross-platform applications.
Worklight Device Runtime Components
A runtime environment with consistent APIs that can work across different mobile platforms to access native device functionality, and integrate with existing services and security.
Worklight Server A runtime server that enables secure access to enterprise services, application version management, unified push notifications, and direct application updates.
Worklight Console A web-based user interface for real-time analytic, push notification authoring, and mobile application version management.
Worklight Application Center
A private, cross-platform mobile application store that is tailored for the specific needs of an application development team.
 
Note: Android applications developed in this book use Worklight Studio and Worklight Device Runtime Components. More details about application development are included in section 5.8, “Developing an MQTT hybrid application for Android” on page 143.
5.3.1 IBM Worklight Studio
Worklight Studio is an Eclipse-based integrated development environment (IDE) that provides a set of tools to create a fully operational mobile application for various mobile operating systems, and to integrate applications with existing services. By enhancing Eclipse with custom plug-ins, Worklight enables developers to use a single IDE to build enterprise applications, from server applications to applications for different mobile device operating systems.
Figure 5-4 illustrates an overview of IBM Worklight Studio.
Figure 5-4 IBM Worklight Studio overview
Worklight Studio provides powerful capabilities mobile applications developers. The following list includes a few of these capabilities:
Pure native development and web development technologies
Worklight Studio supports pure native development and web development technologies, such as HTML5, Apache Cordova, and Java. Developers can develop mobile applications with pure HTML5, or use a compatible JavaScript framework, such as jQuery Mobile, Dojo, or Sencha Touch. This simplifies development with the reusable user interface widgets and commonly used functions that are provided by the frameworks.
Developers can use Apache Cordova to enable mobile application to access native device functionality. Also, if the application needs to access a special device module, such as one for near field communication (NFC), developers can develop a native extension that can be made available to JavaScript through an Apache Cordova plug-in (a small native-to-JavaScript wrapper).
Shell development
For hybrid mobile applications, Worklight uses a default hybrid shell that offers all of the capabilities necessary to use web and native technologies. Shell development enables organizations to separate native component implementations from web-based implementations, and to split this work between different developers.
For instance, by creating a custom shell, developers can add third-party native libraries, implement custom security, or provide extended features specific to the organization. Shells can also be used to restrict or enforce specific corporate guidelines, such as design or security rules. For example, a shell can be used to add a default style to the mobile application, or to disable the device’s camera.
Optimization framework
With IBM Worklight Studio, a common environment is used as a central development point, and all environments can share the same base code. Then, to create an optimized version for an Apple iPad tablet, for instance, developers can create a variant of the base and implement only the required changes. An optimization framework called runtime skinning enables mobile applications to switch at run time between different sets of customization.
Integration of device-specific software development kits (SDKs)
Each vendor of mobile devices supplies its own development environment as part of an SDK. Worklight Studio generates a project for each supported SDK (for example, Xcode for iOS development). Some vendors require developers to use their SDK for specific tasks, such as building the binary application.
The integration of device-specific SDK with Worklight Studio links the Worklight Studio project with the native development environment (such as Xcode), enabling the developer to seamlessly switch between a native development environment and Worklight Studio. Any change in the native development environment is mirrored back to the developer’s Worklight Studio project, reducing the need for manual copying.
Third-party library integration
Depending on the developer’s programming approach, these mobile applications can include several JavaScript frameworks, such as Sencha Touch, jQuery, or Dojo. This third-party library integration promotes code reuse and reduces implementation times.
Many companies underestimate the effort involved in developing a framework, because testing efforts for quality assurance are not fully taken into account. In the case of a shell project, different kinds of compatible native code or libraries can be included.
Integrated build engine
The build chain of Worklight Studio combines common implementation code (used on all target platforms) with platform-unique code that is used on specific target platforms. At build-time, the integrated build engine of Worklight Studio combines these two implementations into a complete mobile application. This reduces IT development costs by using a single, common implementation for as much of the mobile application as possible, rather than a unique implementation for every supported platform.
Integrated development tools
By extending the Eclipse IDE with custom plug-ins, Worklight Studio can be used to develop all components of a mobile application, including the mobile application and integration modules (called Worklight adapters) from within the same development environment. Integrated development tools allow developers to develop and test these adapters seamlessly in Worklight Studio.
Mobile browser simulator
IBM Worklight Studio offers a mobile browser simulator, which can be used during the development cycle to test mobile web and hybrid applications using a desktop browser. Many of today’s desktop and mobile browsers are based on the WebKit engine as the underlying core technology, providing a common platform for developing applications that support HTML5, CSS3, and JavaScript.
This consistent browser engine enables developers who host their mobile browser simulator on a WebKit-based desktop browser, such as Chrome or Safari, to validate the application behavior before deploying it on the actual device.
When the developer is ready to test on the actual device or mobile emulator, they can verify that the core WebKit engine resident on many mobile devices, including Android and iOS, provides the same consistent user experience that was verified when testing using the browser.
In addition to supporting cross-platform browser testing for mobile devices, the mobile browser simulator also provides implementations of the various Apache Cordova APIs. With these APIs, users can test hybrid applications that use device features without having to run on the actual device, decreasing development time and effort required to repeatedly deploy the application to a device.
Worklight studio is based on Eclipse, so it gives developers all of the flexibility and extensibility that Eclipse provides, such as adding new functionality with plug-ins. For instance, an IBM Rational® Team Concert plug-in can be used to control application source code, track changes, and create daily builds without installing an additional development application.
Worklight Studio also provides a set of Ant tasks that can be used to run a mobile application build for various platforms. Developers can distribute build tasks to a variety of build machines running Apple OS X (for an Apple iOS binary) or Microsoft Windows (for a Microsoft Windows Phone 8 binary), among others.
Using this mechanism can reduce IT resource requirements, because developers no longer need access to multiple build machines to create binaries for specific mobile platforms.
5.3.2 IBM Worklight Device Runtime Components
Worklight Device Runtime Components ensure that the mobile applications have access to a variety of Worklight features during run time. Its components are on the mobile device, and consist of libraries that are bundled into the application to enable additional runtime capabilities.
These libraries can help integrate mobile applications with Worklight Server using predefined communication interfaces, and simplify application development by providing unified access to native device functionality.
The native, hybrid, mixed hybrid, or web-based APIs in Worklight Device Runtime Components provide support for all mobile development approaches, with enhanced security and integration features. For hybrid and mixed hybrid applications, the included Apache Cordova plug-ins add native capabilities and cross-platform user interface controls.
Worklight Device Runtime Components deliver a uniform bridge between web technologies (HTML5, CSS3, and JavaScript) and the native functions available on various mobile platforms. Figure 5-5 illustrates how the architecture of Worklight Device Runtime Components combines native and web technology to drive mobile application development.
Figure 5-5 Worklight Device Runtime Components: Architecture overview
Worklight Device Runtime Components support a wide variety of mobile operating systems and release levels (some are only supported at certain fix pack levels). See the most recent list of supported mobile operating systems and release levels at the following website:
In addition to Apache Cordova, Worklight Device Runtime Components provide several important features that can improve application development by reducing complexity and implementation time:
Cross-platform compatibility layer
A cross-platform compatibility layer supports development for all supported platforms. Developers of hybrid mobile applications can access common control elements, such as tab bars and clipboards, and native device capabilities, such as the location service or the camera. These functions can be extended for Android and iOS using a custom shell.
Client-to-server integration
This feature enables transparent communication between a mobile application (built using Worklight technology) and Worklight Server. Worklight forces mobile applications to use a Secure Sockets Layer (SSL)-enabled connection to the server at all times, including for authentication. This integration enables advanced management and security features, such as remotely disabling a specific application version, or updating the web resources of a hybrid application.
Encrypted data store
Mobile devices are inherently insecure, so malicious application users can sometimes get access to private application data or other information. To help prevent this access, an application can store private data in an encrypted data store on the device, and can access that data using a simple API. Using an encrypted data store prevents malicious users from reading the information; all they get is highly encrypted data.
Using International Organization for Standardization (ISO)/International Electrotechnical Commission (IEC) 18033-3 security standards, such as Advanced Encryption Standard (AES) 256 or Public Key Cryptography Standards (PKCS) #5, the encryption complies with the United States National Security Agency (NSA) regulations for transmitting confidential or secret information.
The key that is used to encrypt the information is unique to the current user of the application and the device. Worklight Server issues a special key when a new encrypted data store is created. That makes it almost impossible to reconstruct the key used to encrypt the critical information.
JavaScript Object Notation (JSON) Store
To synchronize mobile application data with related data on the back end, Worklight includes a JSON Store that provides a synchronizable, offline-capable, key-value database. It implements the application’s local read, write, update, and delete operations, and can use Worklight adapter technology to synchronize the related back-end data.
Imagine a sales representative who is making a sales call in an area without reliable network connectivity. The representative can download all customer information, sales documents, and marketing presentations before leaving the office. Then, when the deal is complete and network connectivity is re-obtained, the back-end systems can be updated with all changes related to the new sale.
Runtime skinning
This feature helps developers incorporate an adaptive design that can be tailored to each mobile device. The Worklight runtime skin is a user interface (UI) variant that can be applied during application run time based on device properties, such as the operating system, screen resolution, and form factor. This type of UI abstraction enables mobile application development for multiple mobile device models at the same time.
Reporting
Worklight Device Runtime Components have a reporting feature for application usage and user behavior. The mobile application sends events to Worklight Server, which records the information in a separate database where it can be used by Worklight Console or an external analytic tool, such as IBM Tealeaf® CX Mobile. This enables developers to study which features of the mobile application are being used, and how they are being used.
Worklight APIs
These APIs provide access to Worklight functions across multiple device platforms. Applications built using web technologies can access the Worklight Server through these APIs using JavaScript, but applications that use native components can access the APIs directly using Java and Objective-C.
This enables mobile applications developed with the hybrid and native development approaches, including those running Android, iOS, or Java ME, to benefit from the simplified application security and integration features of Worklight.
5.4 Mobile technologies
This section of the chapter describes various mobile technologies that are referred to when building mobile hybrid applications for MQTT.
5.4.1 Android software stack
The Open Handset Alliance (OHA) that developed Android consists of well-known companies, such as Google, Motorola, Intel, and so on. Android is a software stack for mobile devices. It includes an operating system, middleware, and key applications.
The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform, using the Java programming language. These include a device emulator, tools for debugging, memory and performance profiling, and a plug-in for the Eclipse development environment.
Figure 5-6 illustrates the major components of the Android operating system within the application framework, libraries, Android run time, and Linux kernel.
Figure 5-6 Android software stack
5.4.2 Device API specification
Device APIs enable you to develop mobile applications and widgets that interact with device services, such as calendar, contacts, and camera. For more details about the device APIs specification, see the w3c specification website:
5.4.3 Apache Cordova
Web technologies based on JavaScript are the distinct candidates for the web side of a typical mobile application, and are platform-independent by their nature. Unfortunately, their scope is confined within the web part of the application.
When dealing with the native functionality running on the device platform (Camera, Internal Contacts List, and so on), JavaScript does not prove to be helpful. When the need arises for a web page to obtain or run native functionality, the following alternatives are available:
Implement the scenario in the platform-specific manner (using Android or iOS, for example).
Use a bridge between web pages and the native page, where requests and responses to and from web and native pages are translated by both sides of the bridge.
Choosing the first option, you can create platform-dependent applications. This is a poor choice for enterprise mobile solutions, because the need to implement mobile applications on different platforms leads to cost-ineffective solutions, which are also poorly extensible for future needs. Using the second option, you benefit from overall control on the web-native communication flow, but still keep the solution platform-independent.
Apache Cordova is an open source mobile development framework that enables the creation of cross-platform mobile applications to access native device features over a uniform API using web technologies (HTML5, CSS, and JavaScript).
Targeting multiple mobile platforms and a variety of form factors in a cost-effective manner is a major consideration when developing a mobile platform. To help achieve this capability, Apache Cordova framework comes embedded in Worklight.
The following list includes some advantages of the Apache Cordova Approach:
An open, standards-based approach to cross-platform application development
Cost-effective development accessing existing in-house knowledge and skills
Compatibility with JavaScript toolkits, such as JQuery Mobile, Sencha Touch, and Dojo Mobile
Access to native device features using a uniform JavaScript bridge
An extensible architecture that simplifies integration with native device code
For more details about Apache Cordova, see the following website:
5.4.4 HTML5
HTML5 is a language designed to organize web content. It is intended to make web design and development easier by creating a standardized and intuitive user interface markup language. HTML5 provides the means to analyze and compartmentalize your pages. It enables you to create discrete components that are designed to organize your site logically, and created to give your site syndication capabilities.
HTML5 might be called the information mapping approach to website design, because it incorporates the essence of information mapping, dividing and labeling information to make it easy to use and understand. This is the foundation of HTML5’s dramatic semantic and aesthetic utility. HTML5 gives designers and developers of all levels the ability to publish everything from simple text content to rich, interactive multimedia to the internet.
HTML5 provides effective data management, drawing, video, and audio tools. It facilitates the development of cross-browser applications for the web and portable devices. HTML5 is one of the technologies driving the advances in mobile cloud computing services, because it provides for greater flexibility, enabling the development of exciting and interactive websites.
It also introduces new tags and enhancements, including an elegant structure, form controls, APIs, multimedia, database support, and significantly faster processing speed.
The new tags in HTML5 are highly evocative, encapsulating their role and use. Past versions of HTML used rather nondescript tags. However, HTML5 has highly descriptive, intuitive labels. It provides rich content labels that immediately identify the content.
For example, the overworked <div> tag has been supplemented by the <section> and <article> tags. The addition of the <video>, <audio>, <canvas>, and <figure> tags also provides a more precise description of the specific type of content.
HTML5 provides the following elements and capabilities:
Tags that describe exactly what they are designed to contain
Enhanced network communications
Greatly improved general storage
Web Workers for running background processes
The WebSocket interface to establish continuous connection between the resident application and the server
Better retrieval of stored data
Improved page saving and loading speeds
Support for CSS3 to manage the GUI, which means that HTML5 can be content-oriented
Improved browser form handling
An SQL-based database API that supports client-side, local storage
Canvas and video, for adding graphics and video without installing third-party plug-ins
The Geolocation API specification, which uses smartphone location capabilities to incorporate mobile cloud services and applications
Enhanced forms that reduce the need to download JavaScript code, allowing more efficient communication between mobile devices and cloud servers
For more details about HTML5, see the following website:
Web storage
Cookies have been around from the inception of JavaScript, so storing data on the web is not a new concept. However, web storage is a much more powerful version of data storage that offers more security, speed, and ease of use. Users can also store large amounts of data in web storage. The exact amount is based on the web browser.
Another advantage of using web storage is that this data is not loaded with every server request. The only limitation is that you cannot share web storage between browsers.
There are two types of web storage objects built into HTML5:
The sessionStorage object stores data for a single session. If the user closes the page or browser, the data is deleted.
The localStorage object stores data with no expiration date. The data remains stored when the web page or browser is closed, depending on the storage amount set for the user’s browser.
Browsers that support web storage have the global variables <sessionStorage> and <localStorage> declared at the window level. Example 5-1 and Example 5-2 illustrate JavaScript examples for <sessionStorage> and <localStorage>.
Example 5-1 SessionStorage JavaScript snippet
// Store value on browser for duration of the session
sessionStorage.setItem('key', 'value'),
Example 5-2 LocalStorage JavaScript snippet
// Store value on the browser beyond the duration of the session
localStorage.setItem('key', 'value'),
WebSockets
WebSockets provides full-duplex communication over a single TCP socket. WebSockets is a component of HTML5, designed to replace existing push-based technologies with the aim of reducing latency and network traffic between client and server.
The protocol operates in two parts:
1. First, a handshake is exchanged between client and server (as an HTTP Upgrade request).
2. Next, data is transferred back and forth in messages that are composed of one or more frames, each having a specified type (for example, UTF-8 text, binary data, or control frames) that is the same for each frame in a message.
The WebSockets protocol is designed on the principle that there ought to be minimal framing (the only framing that exists is to make the protocol frame-based rather than stream-based, and to support a distinction between Unicode text and binary frames). It is expected that metadata will be layered on top of WebSockets by the application layer, in the same way that metadata is layered on top of TCP by the application layer (for example, HTTP).
Conceptually, WebSockets is a layer on top of TCP that performs the following functions:
Adds a web origin-based security model for browsers
Adds an addressing and protocol naming mechanism to support multiple services on one port, and multiple host names on one IP address
Layers a framing mechanism on top of TCP to get back to the IP packet mechanism that TCP is built on, but without length limits
Includes an extra closing handshake in-band that is designed to work in the presence of proxies and other intermediaries
WebSockets is ideal for the following types of applications:
Gaming
Stock ticker
Traffic updates
Telemetry data (MQTT over WebSocket)
Mobile payments
Mobile application gateway
Scoring
5.4.5 Eclipse Paho
The Eclipse Paho project was developed to provide scalable open source implementations of open and standard messaging protocols for various emerging applications in the machine-to-machine (m2m) and Internet of Things (IoT) spaces. One of the major objectives of the Paho project is to provide an effective level of decoupling between devices and applications.
Paho initially started with MQTT publish/subscribe client implementations for use on embedded platforms, but in the future will provide corresponding server support as determined by the community. The current efforts of the Paho project are to support the requirements of m2m integration with web and enterprise middleware and applications.
In order for m2m devices and client developers to integrate, develop, and test messaging components end to end, Paho provides a framework to support testing and development of end to end device connectivity with a server. The MQTT application developed in this chapter uses the Paho Java client implementation.
You can download these client implementation source files from the following website:
For more details about the Eclipse Paho project, see the following website:
5.4.6 SQLite database
SQLite is an open source database. SQLite supports standard relational database features, such as SQL syntax, transactions, and prepared statements. The database requires limited memory at run time, which makes it a good candidate for being embedded into other lightweight runtime engines.
SQLite does not support static data typing, but instead uses column affinity. This means that rather than a data type being a property of a table column, it is a property of the data. When a value is inserted into the database, SQLite examines its type.
If the type does not match that of the associated column, an attempt is made to convert the value to the column type. If this is not possible, the value is stored as its native type. SQLite supports the NULL, INTEGER, REAL, TEXT, and BLOB data types.
SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure, or administration of the database. Developers only have to define the SQL statements for creating and updating the database. Later, the database is automatically managed by the Android platform.
Access to an SQLite database involves accessing the file system. This can be slow. Therefore, performing database operations asynchronously is advisable. If the Android application creates a database, this database is by default saved in the data/data/APP_NAME/databases/FILENAME directory.
To read more details about SQLite database, see the following website:
5.5 MQTT hybrid application for Android using IBM Worklight
This section describes how Worklight Studio can be used to develop a hybrid Android application that sends and receives messages using MQTT.
The approach used is to develop the application in HTML and JavaScript, and to use the Apache Cordova (PhoneGap) libraries provided with Worklight to interface with native code that implements the MQTT protocol. This native code includes an Android Service that manages communications with MQTT when the application is not running in the foreground.
Figure 5-7 illustrates the architecture of the mobile application developed in this chapter. This application is developed as an Worklight hybrid application. User interface and application logic is coded in HTML, CSS, and JavaScript.
Figure 5-7 Architecture of hybrid mobile application
The Worklight Client API enables the mobile application JavaScript code to use Android platform-specific user interface controls, and to access device-specific hardware. The Worklight API uses Apache open source Cordova project (Also known as PhoneGap) to bridge JavaScript to the native Java code required to interface with the Android platform and device hardware.
The same approach has been extended to send and receive messages using MQTT. This way, mobile application programmers can develop their application logic and user interface using regular JavaScript, but the detailed code to handle communications with the messaging service is implemented in native Java code.
To handle the specifics of MQTT protocol, this mobile application uses Java MQTT client implementation from the Eclipse Paho project. This is a general-purpose Java library. It is wrapped with an Android Service to adapt it for use in the Android platform.
One of the major benefits this approach provides is to enable incoming messages to be handled when the application is not running in the foreground. The Cordova plug-in and JavaScript API components serve as the interface between the Android Service and the JavaScript application logic.
 
Note: It is advisable to keep all mobile application-specific logic in the JavaScript portion of the application, rather than developing it in the Cordova plug-in or Android Service components. This approach enables the native and platform-specific components to be reused for other mobile applications.
The integration between MQTT and Worklight is performed in the Device Runtime level. Because Worklight uses the Apache Cordova (PhoneGap) framework to provide cross-platform run time for supported mobile devices, a PhoneGap plug-in must be developed for supporting MQTT.
For more details about developing Apache Cordova plug-ins for MQTT applications, see 5.8.4, “Creating a Cordova plug-in” on page 158.
5.6 Configuring the Android SDK and test environment
The Android SDK provides developers the API libraries and developer tools necessary to build, test, and debug applications for Android.
The Android SDK includes a comprehensive set of development tools. These include a debugger, libraries, a handset emulator based on QEMU, documentation, sample code, and tutorials.
Currently supported development platforms include computers running Linux, Mac OS X 10.5.8 or later, and Windows XP or later. The officially supported IDE is Eclipse using the Android Development Tools (ADT) Plug-in. This section describes the setup of Android SDK on Windows.
Enhancements to Android's SDK are closely integrated with the overall Android platform development. The SDK also supports older versions of the Android platform, in case developers want to target their applications at older devices. Development tools are downloadable components, so after one has downloaded the latest version and platform, older platforms and tools can also be downloaded for compatibility testing.
Android applications are packaged in the .apk format, and stored under the /data/app folder on the Android OS (the folder is accessible only to the root user for security reasons).
Developers can download the Android SDK from the following website:
5.6.1 Android SDK tools
The Android SDK includes a variety of tools that help developers develop mobile applications for the Android platform. The tools are classified into two groups:
SDK tools
Platform tools
The SDK tools are installed with the SDK starter package and are periodically updated. The SDK tools are required by developers for developing Android applications. The following list includes some of the most important SDK tools:
The Android SDK Manager (Android SDK)
The Android Virtual Devices Manager (AVD Manager)
The Android Emulator (emulator)
The Dalvik Debug Monitor Server (DDMS)
Table 5-2 summarizes a list of frequently-used SDK tools.
Table 5-2 Android SDK tools
SDK tools
Description
Android SDK and AVD Manager
Helps you manage AVDs, projects, and the installed components of the SDK
Dalvik Debug Monitor Server (DDMS)
Helps you debug Android applications
dmtracedump
Helps you generate graphical call-stack diagrams from trace log files
Draw 9-patch
Helps you easily create a NinePatch graphic using a what you see is what you get (WYSIWYG) editor
Android Emulator (emulator)
A QEMU-based device emulation tool that you can use to design, debug, and test your applications in an actual Android runtime environment
Hierarchy Viewer (hierarchyviewer)
Helps you debug and optimize an Android application's user interface
hprof-conv
Converts the HPROF file that is generated by the Android SDK tools to a standard format, so you can view the file in a profiling tool of your choice
layoutopt
Helps you quickly analyze your application layouts to optimize them for efficiency
mksdcard
Helps you create a disk image that you can use with the emulator, to simulate the presence of an external storage card (such as an SD card)
Monkey
Runs on your emulator or device and generates pseudo-random streams of user events, such as clicks, touches, or gestures, and several system-level events, and can be used to stress test the application in a random yet repeatable manner
monkeyrunner
Provides an API for writing programs that control an Android device or emulator from outside of Android code
ProGuard
Shrinks, optimizes, and obfuscates application code by removing unused code and renaming classes, fields, and methods with semantically obscure names
Systrace
Helps you analyze the execution of applications in the context of system processes, to help diagnose display and performance issues
sqlite3
Helps you access the SQLite data files created and used by Android applications
traceview
Provides a graphical viewer for execution logs saved by application
zipalign
Optimizes .apk files by ensuring that all decompressed data starts with a particular alignment relative to the start of the file
Platform tools
The platform tools are installed with the SDK platform. Platform tools are compatible with earlier platform versions. Developers typically use only one of the platform tools: The Android Debug Bridge (ADB). ADB is an important tool that helps developers manage the state of an emulator instance or Android powered devices.
Developers can also install an Android application (.apk) file on a device using ADB. The other platform tools are typically called by the Android build tools or ADT, so developers rarely need to start these tools directly.
 
Note: Before installing the Android SDK, verify the system requirements for this tool. You can obtain the Android SDK system requirements from the following website:
5.6.2 Downloading and installing the ADT bundle
Complete the following steps to install ADT:
1. Download the Android SDK bundle from the following website:
2. Extract the bundle in a dedicated directory on the file system.
3. After the .zip file is extracted, you see the files and folders, as shown in Figure 5-8.
Figure 5-8 Android SDK bundle
4. Click eclipse → eclipse.exe.
5. Provide the workspace location to open a new development workspace.
6. A new workspace is started for application development.
7. Click the Android SDK Manager icon in the Java perspective, as shown in Figure 5-9.
Figure 5-9 Android SDK Manager
8. Select packages in the Android SDK Manager tool and click Install <number> Packages, as highlighted in Figure 5-10. After the packages are installed, Android application on API level 18 can be developed.
Figure 5-10 Android SDK Manager and package updates
9. Now you can install Worklight Studio and create Android SDK test emulator.
5.6.3 Installing IBM Worklight studio in Android SDK
You can install and configure the Worklight Developer Edition within Android SDK. You must install Eclipse Marketplace client first.
Configuring Eclipse Marketplace client
Complete these steps to configure the Eclipse Marketplace client:
1. In Android SDK, click Help → Install New Software.
2. Select the Eclipse Juno repository:
3. Select General Purpose Tools → Marketplace Client, and then click Next.
4. Accept the license and install Eclipse Marketplace client.
5. When the Eclipse Marketplace client is installed, restart Android SDK.
Figure 5-11 shows the Eclipse Marketplace client, now available in the Help menu of Android SDK.
Figure 5-11 Marketplace client in Android SDK
Installing IBM Worklight Developer Edition
Complete the following steps to install IBM Worklight Developer Edition:
1. In Android SDK, click Help → Eclipse Marketplace.
2. Click Search → Find text box.
3. Enter Worklight Developer Edition then click the Search icon.
Figure 5-12 shows the search result returned after searching for the text Worklight Developer Edition.
Figure 5-12 Search results for IBM Worklight Developer Edition
4. Click Install.
5. In the Confirm Selected Features dialog, leave everything selected, and click Next.
6. In the Review License dialog, accept the license terms and click Finish.
7. In the dialog prompting to restart Eclipse, click Yes.
8. When the IBM Worklight Developer Edition is installed, and Android SDK is restarted, switch to the Design perspective.
9. Select Window Open Perspective → Other → Design. Click OK.
 
Note: All development steps for this hybrid application are performed in the Design perspective of Worklight Studio. If you are required to change the perspective in the development tool, that will be clearly stated.
5.6.4 Configuring the Android emulator
Android emulator is a QEMU-based device-emulation tool that developers can use to design, debug, and test their applications in an actual Android runtime environment. This section describes steps to configure an Android device emulator:
1. In the Android SDK tool Java perspective, click Android Virtual Device Manager, as shown in Figure 5-13.
Figure 5-13 Android Virtual Device Manager
2. Complete the Android Virtual Device creation wizard, as shown in Figure 5-14 on page 129:
a. Enter ITSOTransportPhone as the AVD Name.
b. Set the Device to 4.0” WVGA (480 X 800: hdpi).
c. Set the Target to Android 4.3 - API Level 18.
d. Set the CPU/ABI to ARM (armeabi-v7a).
e. Select Size in GiB and enter 2 (this is required because the MQTT plug-in uses the SD card for persistence).
f. Click OK.
Figure 5-14 Android Virtual Device creation wizard
When the Android Virtual Device creation completes, a new device named ITSOTransportPhone is available in Android Virtual Device Manager.
5.7 MQTT hybrid application use case and requirements
5.8, “Developing an MQTT hybrid application for Android” on page 143, describes the process and procedure to develop the MQTT hybrid application for Android. However, it is important to understand the functional requirements and use cases for the application developed. This section describes company’s business profile, their business problems, requirements and use case for a mobile application.
5.7.1 About the company
This mobile application is developed for a hypothetical company called ITSO Transport Corporation. This company provides transport services to grocery retailers around the country. Trucks from this company are scheduled to pick up groceries from centralized cold storage and deliver groceries to the end retail stores using trucks enabled with cold storage containers.
Timely delivery of groceries is the key success attribute for ITSO Transport Corporation business, and it helps build their customer satisfaction. Every truck scheduled for delivery is equipped with two crew members, a truck driver and an assistant.
5.7.2 Business problem
Timely deliver of groceries is critical to ITSO Transport company. Any delay during the delivery can cause groceries to get stale. The company observes that deliveries are obstructed by a variety of problems on the highway. The following list includes a few of the key problems:
Trucks get into problems, such as flat tires, problems with container cold storage, road accidents, and so on, for which truck drivers need immediate roadside assistance. If truck drivers need to schedule and coordinate assistance accurately and correctly on their own, that takes much of their time and can cause further delivery delay.
Truck drivers who are not aware of traffic congestion and weather problems on their delivery route can get engaged with unexpected problems and cause delivery delays.
5.7.3 Application requirements
ITSO Transport corporation wants to develop an Android mobile application for the Android devices installed in delivery trucks. This mobile application must fulfill the following functional requirements:
Authenticate the truck driver using a driver user name and password.
Authorize the mobile application with the connection and messaging policies of IBM MessageSight.
Truck drivers log in to this application before starting on a delivery, and log out from this application when they get the truck back to the station. The mobile application makes durable subscriptions on topics when drivers log in to the application, and unsubscribes from the same topics when a logout is performed.
The mobile application captures changes in the geographic location of the truck, and transmits that data to back-end IBM MessageSight, with the longitude and latitude of the truck’s location.
The truck’s assistant can request roadside assistance using the mobile application.
The roadside assistance request message includes the type of assistance required, and the geographic location of the truck where assistance needs to be dispatched.
The roadside assistance request and response message must be sent with the highest quality of service (QoS2), for exactly once delivery of these critical messages.
Based on the truck’s location as captured by back-end services, back-end services send push notifications to the mobile application, alerting drivers for any predicted problems on their destination route. These push notifications might be weather notifications, traffic-related alerts, or weigh station reminders. Example 5-3 shows examples of these critical alerts.
Example 5-3 Push notification example
 – Inclement weather in your area, drive safely and inform main office if you expect delivery to be delayed
 – Highway construction on I-75, use alternative route if possible
 – Tornado Warnings issued in your area, take cover immediately
 – Truck malfunction in your area, inform front office if you are available to pick up load for delivery
 – Traffic Jam reported on Highway 5, use alternative route
 – Accident on Interstate 10, take alternative route
 – Heavy snow - use precaution and engage inclement weather driving gear
 – Bay bridge is closed, plan alternative route
 – Highway 92 closed, take alternative route
 – Return to station, additional cargo is ready for delivery
Push notifications must only be sent to relevant trucks, whose truck location matches the business event.
Push notifications are also sent with QoS2 quality of service, for exactly once delivery of notification to the mobile application in the truck.
Broadcast of important messages is possible, which enables the back-end office team to broadcast important communication to all of the trucks currently delivering or scheduled for delivery. Example 5-4 shows examples of these broadcast messages.
Example 5-4 Broadcast messages to all trucks
- Drive safely and abide by state traffic laws.
- It is month end and your salary is deposited in your bank account.
- Bring truck to nearest service station, for routine service check.
Broadcast messages must be sent with at least once delivery quality of service (QoS1). These messages are marked as retained publication, and when drivers log in to the mobile application before starting on a delivery, they will receive the previously broadcast message.
5.7.4 Application use cases
Figure 5-15 shows actors and use cases for ITSO Transport mobile application.
Figure 5-15 Use case diagram for ITSO Transport mobile application
Actors
The following list includes the main actors in context of the ITSO Transport mobile application:
ITSO truck driver and truck assistant staff
ITSO Transport mobile application
IBM MessageSight server
Use cases for ITSO truck driver and truck assistant staff
The truck driver and the truck assistant staff can use the application to perform the following tasks:
Enter credentials
Truck driver logs in to the mobile application before starting for a delivery, and log out when back to the station after completing the delivery. The truck driver submits a user name and password for authentication, and a truck number for authorization. These credentials are used by the mobile application to establish secure connectivity with IBM MessageSight server. The truck number is used as a client identifier.
Send roadside assistance request
Truck staff must be able to request roadside assistance for any problems with the truck. The assistance message includes the type of request needed, and the geographic location where the assistance needs to be dispatched.
Receive roadside assistance response
A response message as an acknowledgment to an assistance request is received on the mobile application for the staff in truck.
Receive notification messages
Based on the geographic location, the truck staff receives notifications from the back-end office. These notifications make truck staff aware of any problems predicted on their delivery route.
Receive broadcast messages
The back-end office might want to send broadcast messages to all of its truck staff delivering groceries. The truck staff receives these broadcast messages through the mobile application.
Use cases for the ITSO Transport mobile application
The ITSO Transport mobile application include the following functions:
Secure connection
The mobile application establishes secure connectivity using an IBM MessageSight message on an IBM MessageSight server. To establish this connectivity, the mobile application provides driver credentials (user name and password) for authentication, and the truck number for authorization. The truck number is used as a client identifier for this mobile application.
Publish geographic location change
The mobile application publishes any changes to the geographic location of the truck to the back-end IBM MessageSight server on a specific topic string.
More details about the topic string used for publish and subscribe in the ITSO Transport mobile application are included in 5.7.6, “Topic strings used for publish and subscribe” on page 138.
Publish roadside assistance request
The mobile application publishes a roadside assistance request, from the truck driver to the back-end IBM MessageSight server, as a publication on a specific topic string.
Subscribe roadside assistance response
The mobile application subscribes to the topic string on which the roadside assistance response will be received. The roadside assistance response message received from the IBM MessageSight server is alerted and displayed through the assistance request tab in the mobile application.
Subscribe notification messages
The mobile application subscribes to the topic string on which the push notification specific to this truck will be received. The push notification message received from the IBM MessageSight server is alerted and displayed through the notification tab in the mobile application.
Subscribe broadcast messages
The mobile application subscribes to the topic string on which the broadcast messages from the back-end office will be received. The broadcast message received from the IBM MessageSight server is alerted and displayed through the notification tab in the mobile application.
Use case for the IBM MessageSight server
The application uses IBM MessageSight server for the following functions:
Secure connection
The IBM MessageSight server receives a secure MQTT connection request from the ITSO Transport mobile application. After authentication and authorization is completed, a secure connectivity is established between the mobile application and the IBM MessageSight server.
Geographic location changes
The IBM MessageSight server receives publications from mobile applications, on a specific topic, for changes to the geographic location of the truck. These messages are later published to the back-end application, which has subscribed on a matching topic string.
Roadside assistance request
The IBM MessageSight server receives publications from the mobile application, on specific topics, for roadside assistance requests from the truck staff. These messages are later published to the back-end application, which has subscribed on a matching topic string.
Roadside assistance response
The IBM MessageSight server receives a publication from the back-end enterprise application, on a specific topic, for a response to a corresponding roadside assistance request received from the mobile application. This response message is later published to the mobile application that sent the assistance request and has subscribed on a matching topic string.
Notification message
The IBM MessageSight server receives a publication from the back-end enterprise application, on a specific topic, to send a notification message to a specific truck. The notification message is later published to the mobile application, which has subscribed on a matching topic string.
Broadcast message
The IBM MessageSight server receives a publication from the back-end enterprise application, on a specific topic, to send broadcast messages to all trucks currently delivering groceries. The broadcast message is later published to the mobile application, which has subscribed on a matching topic string.
5.7.5 Application visual blueprint
The ITSO Transport mobile application provides several features:
Secure connectivity of the application to the IBM MessageSight server
Road assistance request and response for truck staff
Notification and broadcast message from the back-end office for truck staff
History log of publication, subscription, and connection to IBM MessageSight
These features are provided through different tabs in this mobile application. Figure 5-16 and Figure 5-17 on page 138 show the different tabs and user interfaces to be developed in the ITSO Transport hybrid mobile application.
Figure 5-16 Secure login and assistance request tabs in the mobile application
Figure 5-17 shows the mobile application notifications and history.
Figure 5-17 Push notification and broadcast and log history tabs in the mobile application
5.7.6 Topic strings used for publish and subscribe
The topic string is the label attached to an application message that is matched against the subscriptions known to the IBM MessageSight server. The application message is sent to each client with a matching subscription. To read more details about the MQTT topic name, see Appendix A, “MQTT protocol” on page 303, or the MQTT specification document on the following website:
The ITSO Transport mobile application uses various topics to publish application messages to the back-end IBM MessageSight server, and to subscribe on multiple topics to receive messages from the back-end enterprise applications. This section provides information about a list of these topics.
 
Note: The truck number is not part of the published message payload from the mobile application, because the truck number is already included in the topic.
Geographic location change message
The ITSO Transport mobile application publishes a message when there is a geographic location change for the truck. This message is in comma-separated value (CSV) format, as shown in Example 5-5. The message contains the current time stamp, driver user name, current longitude coordinates, and current latitude coordinates.
Example 5-5 Message format for geographic location changes
TimeStamp,driver username,longitude,latitude
This message is published on the topic mentioned in Table 5-3.
Table 5-3 Topic string for capturing geographic location changes
ITSO Transport mobile application
Direction of message delivery through IBM MessageSight
Back-end enterprise application
Action: PUBLISH
Topic: /itso/driver/geolocation/<Truck Number>
QoS of messages: 0
Retained: No
Protocol: MQTT
Note: This topic is used to publish changes in the geographic location of truck.
 
 
 
 
----------------------------->
 
 
 
 
 
Action: SUBSCRIBE
Topic:
/itso/driver/geolocation/+
Protocol: JMS
Roadside assistance request message
The ITSO Transport mobile application enables its drivers to send roadside assistance requests for several scenarios:
Flat truck tires, and truck staff needs truck mechanical assistance
Container AC malfunction, need assistance from an engineer
Truck in accident situation and truck staff needs emergency assistance
The roadside assistance request is in CSV format, as shown in Example 5-6.
Example 5-6 Message format for roadside request assistance
TimeStamp,driver username,longitude,latitude,text message from driver
The roadside assistance request message contains the current time stamp, driver user name, current longitude coordinates, current latitude coordinates, and a customized text message that the driver can type in the Android application.
Table 5-4 provides details about various topics that are used for sending roadside assistance requests. There are three different topics about which a request can be sent, depending on the assistance required.
Table 5-4 Topic string for roadside assistance request
ITSO Transport mobile application
Direction of message delivery through IBM MessageSight
Back-end enterprise application
Action: PUBLISH
Topic:
/itso/driver/assistance/request/FlatTire/<TruckNumber>
QoS of messages: 2
Retained: No
Protocol: MQTT
Note: This topic is used to publish an assistance request for a flat tire problem.
 
 
 
 
----------------------->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Action: SUBSCRIBE
Topic:
/itso/driver
/assistance/request/#
Protocol: JMS
 
 
 
 
 
 
 
 
 
 
 
 
 
Action: PUBLISH
Topic:
/itso/driver/assistance/request/ACMalfunction/<TruckNumber>
QoS of messages: 2
Retained: No
Protocol: MQTT
Note: This topic is used to publish an assistance request for an AC malfunction problem.
 
 
 
 
 
----------------------->
 
Action: PUBLISH
Topic:
/itso/driver/assistance/request/Accident/<TruckNumber>
QoS of messages: 2
Retained: No
Protocol: MQTT
Note: This topic is used to publish an assistance request for an accident-related emergency.
 
 
 
 
 
----------------------->
 
 
Roadside assistance response message
For a roadside assistance request sent by the ITSO Transport mobile application, there will be a corresponding response received from the back-end enterprise application. To get a response, the ITSO Transport mobile application must subscribe on a topic string, as shown in Table 5-5. The data received is in plain UTF-8 characters with no specific format.
Example 5-7 shows examples of a few response messages sent back to the mobile application.
Example 5-7 Sample messages for a roadside assistance response
- <driver username>, Vehicle mechanic dispatched to your nearest location.
- <driver username>, AC Engineer dispatched to your nearest location.
- <driver username>, Emergency staff notified and dispatched to your nearest location.
Table 5-5 Topic string for roadside assistance response
ITSO Transport mobile application
Direction of delivery through IBM MessageSight
Back-end enterprise application
Action: SUBSCRIBE
Topic:
/itso/driver/assistance/
response/<TruckNumber>
Subscription’s maximum QoS: 2
Protocol: MQTT
Note: This topic is used to receive responses for roadside assistance request.
 
 
 
 
<-------------------------
 
Action: PUBLISH
Topic:
/itso/driver/assistance/
response/<TruckNumber>
Retained: No
Protocol: JMS
Push notification messages from the back-end application
Based on the geographic location of trucks as captured by the back-end application, truck drivers can automatically notify the truck staff about any emergency or business-related situations through notification messages. There is no specific format for these messages, and a few examples of them were provided in Example 5-3 on page 131.
Table 5-6 shows the topic string on which the ITSO Transport mobile application receives push notifications from the back-end enterprise applications.
Table 5-6 Topic string for push notification messages
ITSO Transport mobile application
Direction of delivery through IBM MessageSight
back-end enterprise application
Action: SUBSCRIBE
Topic:
/itso/driver/notification
/<TruckNumber>
Subscription’s maximum QoS: 2
Protocol: MQTT
Note: This topic is used to receive push notification message from back-end enterprise applications.
 
 
 
 
<-------------------------
 
Action: PUBLISH
Topic:
/itso/driver
/notification/
<TruckNumber>
Retained: No
Protocol: JMS
Broadcast messages from the back-end application
The ITSO Transport back-end office team can send broadcast messages to the mobile application in trucks. These messages are intended for all of the drivers currently delivering groceries or who are scheduled for later delivery. These are generally non-critical messages.
Therefore, the messages are sent with QoS1 and marked as retained, so when a driver logs in to the application before delivery, he still receives the previously broadcast message. Example 5-4 on page 132 showed a few examples of these broadcast messages.
Table 5-7 shows the topic string on which the ITSO Transport mobile application receives broadcast messages from the back-end office team.
Table 5-7 Topic string for broadcast messages
ITSO Transport mobile application
Direction of delivery through IBM MessageSight
Back-end enterprise application
Action: SUBSCRIBE
Topic:
/itso/driver/notification
/AllTrucks
Subscription’s maximum QoS: 1
Protocol: MQTT
Note: This topic is used to receive broadcast message from back-end office team.
 
 
 
 
<-------------------------
 
Action: PUBLISH
Topic:
/itso/driver
/notification/AllTrucks
Retained: Yes
Protocol: JMS
5.8 Developing an MQTT hybrid application for Android
This section describes the process and procedure to develop an MQTT hybrid application for Android platform using IBM Worklight Studio. You learn about the development process through an example. The steps described in this section are applicable for other similar application development, not just specific for the example provided in this chapter.
You can download this example from the IBM Redbooks website. For the download instructions, see Appendix D, “Additional material” on page 341.
Figure 5-7 on page 120 illustrates the architecture of a hybrid mobile application. The components that are primarily described in this section have a yellow background.
Start by creating a Worklight hybrid project in IBM Worklight Studio. This application is developed using the bottom-up approach, and the architecture components are designed, configured, developed in the following order:
1. Create an IBM Worklight project and Worklight environment.
2. Create MQTT client layer using Eclipse Paho client.
3. Create Android services.
4. Create Cordova plug-in.
5. Create application logic and user interface.
6. Create Android manifest.
7. Build and deploy the application.
8. Run and test the application.
5.8.1 Creating an IBM Worklight project and Worklight environment
In this section, you create a new IBM Worklight project for a hybrid application, and then create a Worklight environment for Android platform. Follow these steps to create a Worklight project and environment:
1. Go to the directory where Android SDK was extracted previously.
2. Click eclipse → eclipse.exe.
3. Provide the workspace location to open a new development workspace.
4. In the new workspace started for application development, click Windows → Open Perspective → Others.
5. Select Design perspective and click OK, as shown in Figure 5-18.
Figure 5-18 Design perspective
6. In project explorer view, right-click and select New → Worklight Project, as shown in Figure 5-19.
Figure 5-19 Worklight project
7. In the new Worklight project wizard, enter ITSOTransport as the project name, select Hybrid Application under Project Templates, and then click Next (Figure 5-20).
Figure 5-20 Worklight project name and application type
8. On the next window in the New Worklight Project wizard, enter ITSOTransport as the application name, and then click Finish (Figure 5-21).
Figure 5-21 Worklight application name
9. Open the application-descriptor.xml file from the Project Explorer view (Figure 5-22).
Figure 5-22 The application-descriptor.xml file
10. Update the application display name to ITSO Transport and add a description of the application. Save the changes made in the application-descriptor.xml file.
11. Create a Worklight Environment for the application:
a. In the Project Explorer view, expand the ITSOTransport → apps → ITSOTransport project.
b. Right-click the ITSOTransport → New → Worklight Environment application.
12. A new Worklight Environment wizard opens. Select ITSOTransport as the Project name and Application/Component.
13. Select Android phones and tablets and then click Finish (Figure 5-23).
Figure 5-23 Worklight Environment for Android platform
14. After the new Worklight Environment wizard completes the environment creation, a new project for Android named ITSOTransportITSOTransportAndroid is seen in the Project Explorer view.
5.8.2 Creating an MQTT client layer using the Eclipse Paho client
You can download the Eclipse Paho client from the Eclipse Paho website. The client is also included with the examples for download on the IBM Redbooks website. See the download instructions in Appendix D, “Additional material” on page 341. Download the Ch05.zip file and extract it in your local file system.
 
This Java library implements the client half of the MQTT V3.1 protocol implementation. The Java client runs on any suitable Java run time, from Java 1.5 on, including Android. Separate interfaces are provided for synchronous and asynchronous styles of operation.
The synchronous API supports a style where an operation only returns to the caller when the operation has completed. This is a traditional style that can be used to implement a simple client. However, the blocking nature of this API limits its usage in environments where threads are not allowed to block, or when high performance or large numbers of clients are required.
The asynchronous API supports a different style in which a call returns immediately. The application can then either be notified through a callback when the operation completes, or it can use a token returned to the application to block until the operation completes.
This style of API is better suited to mobile, event-oriented, and high-performing applications. Applications where it might take time to complete an operation, or where a thread must not be blocked, are good candidates for the asynchronous API. This client is a version of the open source MQTT client that is available from the Eclipse.org Paho project.
Import this library in the Android environment of the ITSOTransport hybrid application. Follow these steps to import this library in the project:
1. In Project Explorer view, expand the ITSOTransport project → apps → ITSOTransport application → android → native → libs (Figure 5-24).
Figure 5-24 Location to import the Eclipse Paho client
2. Right-click libs and click Import.
3. In the Import wizard, select File System and click Next (Figure 5-25).
Figure 5-25 Import from file system
4. On the next window in the Import wizard, browse to the ../Ch05/ITSOTransport/android/native/libs directory where the downloaded example for this chapter was extracted.
5. Select the org.eclipse.paho.client.mqttv3.jar file, and then click Finish (Figure 5-26).
Figure 5-26 Import the Eclipse Paho Java client library into the project
6. The Eclipse Paho client library is imported into the ITSOTransport/apps/ITSOTransport/android/native/libs folder in the ITSOTransport project (Figure 5-27).
Figure 5-27 Eclipse Paho Java client library available in the project
To read more details about the packages and classes included in the Eclipse Paho Java client library, see the Javadoc website:
5.8.3 Creating Android services
The function of the Android Service is to take the Eclipse Paho MQTT client and adapt it to run in the Android environment. Complete the following steps to import Android service classes into the ITSOTransport Worklight hybrid application project:
1. In the Project Explorer view, expand ITSOTransport project → apps → ITSOTransport application → android → native → src (Figure 5-28).
Figure 5-28 Location to import the Android service Java classes
2. Right click src and then click Import.
3. In the Import wizard, select File System and click Next (Figure 5-29).
Figure 5-29 Import from File System
4. On the next window in the Import wizard, browse to the ../Ch05/ITSOTransport/android/native/src directory where the downloaded example for this chapter was extracted.
5. Navigate to the service folder in the left tree view, and select all of the Java classes in this folder, and then click Finish, as shown in Figure 5-30.
Figure 5-30 Import the Android Java service class
The function of the Android Service is to take the Eclipse Paho MQTT client and adapt it to run in the Android environment. This implementation is structured into several classes in the com.ibm.mqtt.android.service package, as shown in Table 5-8.
Table 5-8 Android service class
Android service class
Description
DatabaseMessageStore
This is a class that uses the Android SQLite database to hold a store of incoming messages that are en route to being delivered to the application.
MessageStore
This Interface has the mechanism for persisting messages until you know they have been received by the application. DatabaseMessageStore implements this interface.
MqttService
This is the implementation of the Service. It extends the Android Service class.
MqttServiceBinder
This is an ancillary class supporting the MqttService class.
MqttServiceClient
This class contains the bulk of the logic that interfaces to the Paho client.
MqttServiceConstants
This class defines constants that are used by the Service (and also by the Cordova plug-in when it interfaces to the service).
MqttTraceHandler
This is an ancillary class supporting the MqttService class.
MessagingMessage
This Java class is a representation of the Messaging.Message class from JavaScript.
6. After the Android service classes are imported into the project, you see them available in the workspace, as shown in Figure 5-31.
Figure 5-31 Android service class imported in ITSOTransport project
The Android service implements an Android bound service. If the application calls the Eclipse Paho MQTT client code directly from the Cordova plug-in, that code is run as part of the application’s Android activity. An Android phone only has one activity running at any one time, and when the user switches to a new application, or starts talking on the phone, the current activity is stopped and is placed on a stack when another activity runs in its place.
By placing the MQTT client in an Android service, you can ensure that it continues to run even when the application is stopped. It is important for having the split between the Cordova MQTT plug-in (which is part of the activity, and therefore only runs when the application owns the phone’s user interface) and the MqttService, which can continue to run in the background.
These two components communicate with each other using Android’s message passing mechanism (Android refers to these messages as intents), and the asynchronous nature of this mechanism fits well with the asynchronous nature of the JavaScript API described later in this book.
The main reason for wanting a service running in the background is to be able to handle messages that arrive when the application’s activity is stopped. The service queues up these messages in the DatabaseMessageStore, and notifies any Activities that it is associated with that it has a message for them.
If and when an activity restarts, its MQTT plug-in will attempt to deliver these messages to the application. MqttService also includes a rudimentary interface to the Android Status notification service, to alert the user that there are messages waiting.
5.8.4 Creating a Cordova plug-in
The Cordova plug-in is made up of two parts:
The JavaScript portion, which you can find in the android/js/mqttCordovaAndroidClient.js file
The Java component, which you can find in the com.ibm.msg.android.cordova.plugin.MQTTPlugin.Java class
The JavaScript code implements the API outlined earlier in this book. It collects the parameters to be passed across to the Java code, and handles callbacks from the Java code, following the standard pattern for a Cordova plug-in.
The JavaScript portion communicates to the Java portion through a set of Actions (messages sent between JavaScript and Java), as shown in Example 5-8.
The CONNECT, DISCONNECT, SUBSCRIBE, UNSUBSCRIBE, and SEND actions are sent from JavaScript to Java when the corresponding function in the JavaScript API is called by the application. The ACKNOWLEDGE_RECEIPT action is sent when the JavaScript application’s onMessageArrived callback has completed processing an incoming message.
Example 5-8 Cordova plug-in actions
var PLUGIN_ACTION = {
SEND_ACTION : "send",
ACKNOWLEDGE_RECEIPT_ACTION : "acknowledgeReceipt",
UNSUBSCRIBE_ACTION : "unsubscribe",
SUBSCRIBE_ACTION : "subscribe",
DISCONNECT_ACTION : "disconnect",
CONNECT_ACTION : "connect",
GET_CLIENT_ACTION : "getClient",
START_SERVICE_ACTION : "startService",
STOP_SERVICE_ACTION : "stopService",
MESSAGE_ARRIVED_ACTION : "messageArrived",
MESSAGE_DELIVERED_ACTION : "messageDelivered",
ON_CONNECTION_LOST_ACTION : "onConnectionLost",
TRACE_ACTION : "trace",
SET_ON_CONNECT_CALLBACK : "setOnConnectCallbackId",
SET_ON_CONNECTIONLOST_CALLBACK : "setOnConnectionLostCallbackId",
SET_ON_MESSAGE_ARRIVED_CALLBACK : "setOnMessageArrivedCallbackId",
SET_ON_MESSAGE_DELIVERED_CALLBACK : "setOnMessageDeliveredCallbackId",
SET_TRACE_CALLBACK : "setTraceCallbackId",
SET_TRACE_ENABLED : "setTraceEnabled",
SET_TRACE_DISABLED : "setTraceDisabled"
};
 
Remember: The mqttCordovaAndroidClient.js Cordova plug-in implementation and MQTTPlugin.Java are available for download from the IBM Redbooks website. For download instructions, see Appendix D, “Additional material” on page 341.
To set the MQTT Cordova plug-in for ITSOTransport application, follow these steps:
1. Select js (the JavaScript folder) in the Worklight environment of the ITSOTransport application.
2. Right-click it and select Import, as shown in Figure 5-32.
Figure 5-32 Import the Cordova plug-in JavaScript portion
3. Select File System and click Next.
4. Browse to the ../Ch05/ITSOTransport/android/js directory where the downloaded material for this chapter was extracted.
5. Select mqttCordovaAndroidClient.js and click Finish, as shown in Figure 5-33.
Figure 5-33 Import mqttCordovaAndroidClient.js in Android Worklight environment
6. After mqttCordovaAndroidClient.js is imported into the workspace, it is available in the JavaScript folder of Android (js), as shown in Figure 5-34.
Figure 5-34 The mqttCordovaAndroidClient.js file available in the Worklight project
7. To create the Java component of Cordova plug-in, select the src folder in the ITSOTransport application Worklight environment (Figure 5-35), right-click, and select Import.
Figure 5-35 Import Java component of Cordova plug-in
8. Select File System and click Next.
9. On the next window in Import wizard, browse to the ../Ch05/ITSOTransport/android/native/src directory where the example application is extracted.
10. Select the plugin folder in the left tree view, select the MqttPlugin.Java classes from this folder, and then click Finish, as shown in Figure 5-36.
Figure 5-36 Import MqttPlugin.Java into the Android Worklight environment
11. After MqttPlugin.java is imported into the workspace, it is available in the native/src folder of Android, as shown in Figure 5-37.
Figure 5-37 MqttPlugin.Java available in the Worklight project
5.8.5 Creating application logic and the user interface
To implement application logic and the user interface, start by importing CSS, JavaScript images, and HTML files from the downloaded example files:
1. Select the common folder in the Worklight environment of the ITSOTransport application.
2. Right-click it and select import, as shown in Figure 5-38.
Figure 5-38 Import CSS, HTML, JavaScript, and image files
3. Select File System and click Next.
4. On the next window in the Import wizard, browse to the ../Ch05/ITSOTransport/android/common directory where the additional material for this chapter was extracted.
5. Select the common folder in the left tree view to import everything. Select Overwrite existing resources without warning, and then click Finish, as shown in Figure 5-39.
Figure 5-39 Import CSS, HTML, JavaScript, and image files for the ITSOTransport application
6. After the HTML, JavaScript, CSS, and image files are imported, they are available in the ITSO Transport Worklight application workspace, as shown in Figure 5-40.
Figure 5-40 HTML, JavaScript, CSS, and image files for the ITSO Transport application
ITSOTransport CSS file
CSS is a style sheet language used for describing the presentation semantics of a document written in a markup language. CSS is designed primarily to enable the separation of document content from document presentation, including elements, such as the layout, colors, and fonts. Example 5-9 shows the contents of the ITSOTransport.css file.
Example 5-9 ITSOTransport.css
/* Reset CSS */
a, abbr, address, article, aside, audio, b, blockquote, body, canvas, caption, cite, code, dd, del, details, dfn, dialog, div, dl, dt, em, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, html, i, iframe, img, ins, kbd, label, legend, li, mark, menu, nav, object, ol, p, pre, q, samp, section, small, span, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, time, tr, ul, var, video {
margin: 0;
padding: 0;
}
 
/* Worklight container div */
#content {
height: 460px;
margin: 0 auto;
width: 320px;
}
 
form, fieldset, table, tr, td {
background: transparent;
border: 0 none;
font-size: 94%;
font-family: inherit;
outline: 0;
margin: 0;
padding: 0;
vertical-align: baseline;
}
 
form.tabContent {
border: 1px solid #c9c3ba;
padding: 0.5em;
background-color: #f1f0ee;
}
 
form.tabContent.hide{
display: none;
}
ITSOTransport HTML user interface
ITSOTransport JavaScript application logic
5.8.6 Creating the Android manifest file
Every Android application must have an AndroidManifest.xml file in its root directory. The manifest presents essential information about the application to the Android system. This file enables you to configure the permissions needed by the application to access platform services. To read more details about the Android manifest XML file, see the following websites:
You can import the AndroidManifest.xml file from the ../Ch05/ITSOTransport/android/native directory, and overwrite the existing file in the android/native folder of the ITSOTransport application, as shown in Figure 5-41.
Figure 5-41 AndroidManifest file for ITSOTransport application
Example 5-10 shows the contents of the AndroidManifest.xml file, and the permissions defined for accessing Android services.
Example 5-10 AndroidManifest.xml file permissions
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ITSOTransport" android:versionCode="2" android:versionName="1.0.0.1">
<supports-screens android:smallScreens="false" android:normalScreens="true" android:largeScreens="false" android:resizeable="false" android:anyDensity="false"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<permission android:name="com.ITSOTransport.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="com.ITSOTransport.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<application android:label="@string/app_name" android:debuggable="true" android:icon="@drawable/icon">
<activity android:name=".ITSOTransport" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="com.ITSOTransport.ITSOTransport.NOTIFICATION"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity android:name="com.worklight.common.WLPreferences" android:label="Worklight Settings"/>
<service android:name=".GCMIntentService"/>
<service android:name=".ForegroundService"/>
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<category android:name="com.ITSOTransport"/>
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="com.ITSOTransport"/>
</intent-filter>
</receiver>
<service android:name="com.ibm.mqtt.android.service.MqttService"></service>
</application>
<uses-sdk android:minSdkVersion="8"/>
</manifest>
5.8.7 Building and deploying the application
To build and deploy this IBM Worklight hybrid application for MQTT, right-click ITSOTransport and select Run As → Build All and Deploy, as shown in Figure 5-42.
Figure 5-42 Build and deploy ITSOTransport MQTT hybrid application
Deploying an Android application using the Android debug bridge
If you do not want to build the complete project from scratch, you can use the ITSOTransportITSOTransportAndroid.apk binary file available in the ../Ch05/ITSOTransport/bin directory where the additional material for this chapter was extracted.
You can deploy the binary file using the Android debug bridge (adb) SDK tool, which is available in the sdk/platform-tools directory of the SDK installation location. Example 5-11 shows the command to deploy the binary file.
Example 5-11 Deploy Android application using adb
C:AndroidSDKsdkplatform-tools>adb install ITSOTransportITSOTransportAndroid.apk
73 KB/s (1635214 bytes in 21.663s)
pkg: /data/local/tmp/ITSOTransportITSOTransportAndroid.apk
Success
After the application is built and deployed, you are now ready to run and test the application.
5.8.8 Running and testing the application
To run this application, right-click the ITSOTransportITSOTransportAndroid project and select Run As → Android Application, as shown in Figure 5-43.
Figure 5-43 Run the ITSOTransport application
After the application is started, it opens the emulator ITSOTransportPhone created in section 5.6.4, “Configuring the Android emulator” on page 128.
Figure 5-44 shows the ITSOTransport Worklight hybrid application deployed and available in the ITSOTransportPhone emulator.
Figure 5-44 The ITSOTransport Worklight hybrid application deployed
Figure 5-45 shows the ITSOTransport Worklight hybrid application started in the ITSOTransportPhone emulator.
Figure 5-45 The ITSOTransport application started in the Android emulator
This application provides all of the functionality described in section 5.7.4, “Application use cases” on page 133. Use case testing for this hybrid mobile application is performed in the scenario chapters of this book. Chapter 6, “Scenarios overview” on page 175, provides a brief overview of all of the scenarios described in this book.
 
Note: This application is based on the MQTTSample application described in the Using MQ Telemetry Transport Protocol in IBM Worklight Mobile applications IBM technote:
You can also see this technical article to read more details about another IBM Worklight hybrid application developed for MQTT.
The Worklight projects are available for download from the IBM Redbooks website. The download instructions are in Appendix D, “Additional material” on page 341. You can import these projects into IBM Worklight studio and run the ITSOTransport MQTT application developed for IBM MessageSight.
..................Content has been hidden....................

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