Home Mobile JavaScript Mobile Application Development

JavaScript Mobile Application Development

By Hazem Ahmed Saleh Ahmed , Hazem Saleh
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    An Introduction to Apache Cordova
About this book
Publication date:
October 2014
Publisher
Packt
Pages
332
ISBN
9781783554171

 

Chapter 1. An Introduction to Apache Cordova

In this chapter, we will discover the world of Apache Cordova and cover the following topics:

  • What Apache Cordova is

  • The differences between the different mobile development approaches (mobile web, hybrid mobile, and native mobile applications)

  • Why you should use Apache Cordova to develop your mobile applications

  • The basics of Apache Cordova architecture

Finally, we will have a quick overview of the current APIs of Apache Cordova 3.

 

What is Apache Cordova?


The Apache Cordova project is an Apache open source project that targets the creation of native mobile applications using common web technologies such as HyperText Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript. It offers a set of JavaScript APIs, which provide access to a number of natively built core plugins. Cordova offers many core APIs, some of which grant the ability to perform the following:

  • Process the device contact lists

  • Process files on the device storage

  • Capture a photo using the device camera

  • Get a photo from the device gallery

  • Record voice using the device microphone

  • Get device direction using the device compass

  • Retrieve the device locale

  • Find out the device location

  • Get the device motion

  • Get the device connection information

Cordova supports a wide variety of different mobile platforms such as:

  • Android

  • iOS

  • Windows platform:

    • Windows Phone 7 (this support will be removed soon in Cordova Version 3.7)

    • Windows Phone 8

    • Windows 8

  • BlackBerry

  • Tizen

  • Web OS

  • Firefox OS

  • Bada

  • Ubuntu

The Apache Cordova official API documentation is at http://docs.cordova.io.

You can also refer to the following GitHub repositories to find the source code of Apache Cordova implementations on the different platforms:

You will find it very useful to know about GitHub, which is a web-based hosting service for software development projects that use the Git revision control system. GitHub offers both paid plans for private repositories and free accounts for open source projects. The site was launched in 2008 by Tom Preston-Werner, Chris Wanstrath, and PJ Hyett.

 

The differences between mobile web, hybrid mobile, and native mobile applications


It is very important to understand the differences between mobile web, hybrid mobile, and native mobile applications. Mobile web application(s) can be accessed using the web browser and are designed to be responsive. Responsive means that they can adapt their views in order to be displayed properly on different resolutions of mobile and tablet devices. Mobile web applications usually require you to be online in order to use them. They are not real mobile native applications, although they might have the same look and feel as mobile native applications that use the CSS technology. Mobile web applications are, in fact, not uploaded to app stores and do not have the same physical formats of the platform native mobile applications. They use limited native features of the mobile device, such as geolocation and storage features.

Although hybrid and native mobile applications have the same physical formats, they are developed using totally different technologies. Hybrid mobile applications are developed using common web technologies (HTML, CSS, and JavaScript), while native mobile applications are developed using the mobile platform programming language (for example, Java for Android, Objective-C for iOS, and .NET programming language(s) for Windows Phone).

If you are a native mobile application developer, then in order to develop a single native application that can work on the different mobile platforms, you will need to develop your application on one platform and then reimplement its logic on other platforms. Reimplementing the same logic on every platform that you have to support is a pain. This is because you will need to use the mobile platform programming language and handle different types of problems, which you will face on every platform.

Hybrid applications have the great advantage of allowing you to use the same code base (which consists of your HTML, CSS, and JavaScript code) for the different platforms of your application. This means that you write your application code once, and then, you can run it everywhere. Of course, you might need to do specific changes on every platform, but in the end, these changes are mostly minimal. Adding to this advantage, all of your application logic is implemented using a single and neat programming language, which is JavaScript.

The time taken to develop hybrid mobile applications, which run across many mobile platforms, will definitely be shorter. Furthermore, the required resources to implement a hybrid mobile project will be minimized compared to developing native mobile applications. This is because hybrid applications use a unified programming language (JavaScript), while native mobile applications use many non-unified programming languages (such as Objective-C, Java, and C#), which, by definition, require a larger team of developers with different skill sets.

Finally, it is worth mentioning that native mobile applications might be a little bit faster than hybrid applications (assuming that they are implementing the same set of requirements), because native applications are compiled and native code is optimized. However, applying the common best practices in your hybrid applications can definitely increase your application's performance to be as close as the native application. In this book, you will learn how to boost the performance of your hybrid mobile application using Apache Cordova and jQuery Mobile.

If you take a look at the following table, you will find that it summarizes the differences between the three types of mobile applications:

 

Mobile web

Hybrid application

Native application

Uploaded to app store

No

Yes

Yes

Used technologies

JavaScript, CSS, and HTML

The native programming language of the platform

Complexity

Normal

Normal

High

Cross-platform mobiles support

Yes

Yes

No

Device native features

Partial

Full (thanks to Hybrid application frameworks such as Apache Cordova).

Full

Performance (assuming following best practices)

Very good

Excellent

This table summarizes the key differences between mobile web, hybrid mobile, and native mobile applications.

Tip

Apache Cordova is currently one of the most popular frameworks for building Hybrid applications.

From the developers' perspective, if you are a web developer, then creating hybrid applications using Apache Cordova is a great option for you as you will not have to spend time learning JavaScript, CSS, and HTML. Using your existing skill set with Apache Cordova allows you to develop cross-platform mobile applications in less time.

If you are a native developer, then spending some time learning the common web technologies will add great value and have an impact on your work. This is because after acquiring these skills along with Apache Cordova, you will be able to develop cross-platform mobile application(s) in less time and effort compared to the time and effort you would spend in order to develop the same application(s) on every platform using native programming languages.

 

Why you should use Cordova


In order to understand the importance of using Apache Cordova, you first need to understand the current challenges of mobile development, which are summarized as follows:

  • Every mobile platform has its own programming philosophy

  • Every mobile platform has its own set of unique problems

  • Developing, testing, and maintaining native application(s) on different mobile platforms is expensive

One of the biggest challenges of current mobile development is that every mobile platform has its own programming philosophy. There are various programming languages and tools that are required in order to develop mobile applications on the different platforms. For example, if you want to develop a native mobile application on Android, you will need to use Java as the programming language and Eclipse or IntelliJ (or another equivalent Java IDE) as an Integrated Development Environment (IDE). On the other hand, if you want to develop a native mobile application in iOS, you will need to use Objective-C as the programming language and Xcode or JetBrains AppCode as the programming IDE. Finally, if you want to develop a Windows platform mobile application, you will need to use a .NET programming language and Visual Studio as the IDE.

As a result of this previous challenge, developing, testing and maintaining a single application that has different implementations on mobile platforms is really hard and costly. You will have many code bases that are usually inconsistent, because every code base will be written in a different language by developers from different backgrounds. This is because it is really hard to find a single developer who is aware of all of these programming languages and tools.

Tip

Using an IDE to develop mobile applications is not mandatory. However, it is recommended as it speeds up the process of application development and testing.

Adding to these challenges, handling the incompatible behaviors of mobile platforms is a challenge that cannot be ignored. One of the problems that you might face when you develop your native Android application on iOS is that you cannot send SMS messages directly using the platform API without launching the native platform SMS application to the user. On the other hand, in Android, you can send SMS messages using the platform API directly from your application code. This means that you will have the burden of not only implementing your application logic on the different platforms, but you might also need to implement different workarounds using different programming languages in order to have a consistent behavior of your application as much as you can across the mobile platforms.

Using Apache Cordova will reduce the complexity of these challenges. It will give you the ability to use a single programming language (JavaScript) to write your application on the different mobile platforms; you won't need to have a big set of programming languages anymore after using Apache Cordova. Apache Cordova gives you the ability to have a common code base for all of the implementations of your application on the different mobile platforms. This means that the complexity of developing, testing, and maintaining your mobile application will be greatly reduced.

Having a single code base that is developed using JavaScript gives a great flexibility for mobile developers to handle the unique problems of every mobile platform. This puts everything neatly in a centralized place in the code. This makes your application code more readable and maintainable.

 

Cordova architecture


The following diagram includes the main components of an Apache Cordova application (HTML, CSS, and JavaScript files). It can also contain helper files (such as application's JSON resource bundle files). Here, HTML files include JavaScript and CSS files. In order to access a device's native feature, JavaScript application objects (or functions) call Apache Cordova APIs.

Apache Cordova creates a single screen in the native application; this screen contains only a single WebView that consumes the available space on the device screen. Apache Cordova uses the native application's WebView in order to load the application's HTML and its related JavaScript and CSS files.

It is important to note that WebView is a component that is used to display a web page or content (basically HTML) in the application window. We can simply say that it is an embedded mobile web browser inside your native application that allows you to display the web content.

When the application launches, Apache Cordova loads the application's default startup page (usually index.html) in the application's WebView and then passes the control to the WebView, allowing the user to interact with the application. Application users can interact with the application by doing many things such as entering data in input fields, clicking on action buttons, and viewing results in the application's WebView.

Thanks to this technique and because WebView is a native component that provides web content rendering, users feel that they are interacting with a native application screen if the application's CSS is designed to have the mobile platform look and feel.

Tip

WebView has an implementation in all the major mobile platforms. For example, in Android, WebView refers to the android.webkit.WebView class. In iOS, however, it refers to the UIWebView class that belongs to the System/Library/Frameworks/UIKit framework. In the Windows Phone platform, meanwhile, it refers to the WebView class that belongs to the Windows.UI.Xaml.Controls classes.

In order to allow you to access a mobile's native functions such as audio recording or camera photo capture, Apache Cordova provides a suite of JavaScript APIs that developers can use from their JavaScript code, as shown in the following diagram:

The calls to Apache Cordova JavaScript APIs are translated to the native device API calls using a special bridge layer. In Apache Cordova, the device native APIs are accessed from Apache Cordova plugins.

Tip

You will learn how to develop your own custom Cordova plugin in Chapter 6, Developing Custom Cordova Plugins.

The beautiful thing behind this approach is that you can use a unified API interface in order to perform a specific native function (such as camera photo capturing or audio recording) transparently across the various mobile platforms. It is important to note that in order to perform these native functions as a native developer, you will need to call completely different native APIs that are usually implemented using different native programming languages. All of the Cordova JavaScript-unified APIs and their corresponding native code implementations are implemented using plugins. We will illustrate Cordova plugins in much more detail in Chapter 6, Developing Custom Cordova Plugins.

If you are interested to know what will happen when a call is performed to a Cordova JavaScript API, then we can take a look at a complete example for a Cordova API call under Android and Windows Phone platforms. In order to get a complete picture, you simply call the following Cordova JavaScript API:

navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    destinationType: Camera.DestinationType.DATA_URL
});

function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}

function onFail(message) {
    alert('Failed because: ' + message);
}

As shown in preceding code snippet, a simple call to the getPicture() method of the camera object is performed with the following three parameters:

  • onSuccesscallback: This parameter is called if the getPicture operation succeeds.

  • onFailcallback: This parameter is called if the getPicture operation fails.

  • { quality: 50, destinationType: Camera.DestinationType.DATA_URL }: This is a JavaScript object that contains the configuration parameters. In our example, only the two parameters, quality, which refers to the quality of the output picture (it should be a value from 0 to 100), and destinationType, which refers to the format of the return value, are specified. It can have one of the three values: DATA_URL, which means that the format of the returned image will be Base64-encoded string, FILE_URI, which means that the image file URI will be returned, or NATIVE_URI, which refers to the image native URI.

As we set destinationType to Camera.DestinationType.DATA_URL, the parameter of onSuccess will represent the Base-64 encoded string of the captured image.

This simple call to the getPicture() method of the camera object calls the following Android Java native code. Please note that this code is the actual code for the Apache Cordova Camera plugin Version 3. If you are a native Android developer, then the following two code snippets will look very familiar to you:

public void takePicture(int returnType, int encodingType) {
    // Code is omitted for simplicity ...

    // Display camera
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    // Specify file so that large image is captured and returned
    File photo = createCaptureFile(encodingType);
    
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    this.imageUri = Uri.fromFile(photo);

    if (this.cordova != null) {
        this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
    }
}

As shown in the previous code, in order to open a camera in an Android device, you need to start the "android.media.action.IMAGE_CAPTURE" intent and receive the result back using the startActivityForResult() API of the Android Activity class. In order to receive the image capture intent result in Android, your Android Activity class needs to implement the onActivityResult() callback, as shown in the following Apache Cordova Android Camera plugin code:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        
        // If image available
        if (resultCode == Activity.RESULT_OK) {
                // ... Code is omitted for simplicity ...

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
            
                    // ... Code is omitted for simplicity ...

                    this.processPicture(bitmap);
                }

                // If sending filename back
                else if (destType == FILE_URI || destType == NATIVE_URI) {
                    if (this.saveToPhotoAlbum) {
                        Uri inputUri = getUriFromMediaStore();
                        
                        //Just because we have a media URI doesn't mean we have a real file, we need to make it
                        uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
                    } else {
                        uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
                    }
                        
                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }
                        
                    // ... Code is omitted for simplicity ...
                    // Send Uri back to JavaScript for viewing image
                    this.callbackContext.success(uri.toString());
                }
                        
                // ... Code is omitted for simplicity ...
            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }
                        
        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }
                        
        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }
}

If the camera capture operation succeeds, then resultCode == Activity.RESULT_OK will be true, and if the user requires the result of the captured image as a Base-64 encoded string, then the captured bitmap image is retrieved and processed in the processPicture(bitmap) method. As shown in the following code snippet, processPicture(bitmap) compresses the bitmap image and then converts it to a byte array, which is encoded to Base-64 array. This is then finally converted to a string that is returned to the JavaScript Cordova client using this.callbackContext.success(). We will illustrate Android CallbackContext in more detail later in this book.

If the user requires the result of the captured image as a file or native URI string, then the file URI of the image file is retrieved and sent to the JavaScript Cordova client using this.callbackContext.success().

public void processPicture(Bitmap bitmap) {
    ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
    try {
        if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
            byte[] code = jpeg_data.toByteArray();
            byte[] output = Base64.encode(code, Base64.DEFAULT);
            String js_out = new String(output);
            this.callbackContext.success(js_out);
            js_out = null;
            output = null;
            code = null;
        }
    } catch (Exception e) {
        this.failPicture("Error compressing image.");
    }
    jpeg_data = null;
}

Note

In Android native development, an Android Activity class is generally a thing that the user can do. The Activity class is also responsible for the creation of a window for you in which you can place your User Interface (UI) while using the setContentView() API. An Android Intent is an abstract description of an operation to be performed so that it can be used with startActivity or startActivityForResult to launch an activity, as shown in the previous example of Camera photo capturing.

If you are using Microsoft Windows Platform 7 or 8, for example, the call to the getPicture() method of the camera object will call the following Windows Phone C# native code. Please note that this code is the actual code for Apache Cordova Camera Windows Phone plugin. If you are a native Windows Phone developer, the next two code snippets will look very familiar to you:

CameraCaptureTask cameraTask;

public void takePicture(string options)
{
    // ... Code is omitted for simplifying things ...

    if (cameraOptions.PictureSourceType == CAMERA)
    {
        cameraTask = new CameraCaptureTask();
        cameraTask.Completed += onCameraTaskCompleted;
        cameraTask.Show();        
    }
    
    // ... Code is omitted for simplifying things ...
}

As shown in the preceding code, in order to open a camera in a Windows Phone device, you need to create an instance of CameraCaptureTask and call the Show() method. In order to receive the image capture result on the Windows Phone platform, you need to define an event handler that will be executed once the camera task completes. In the previous code, onCameraTaskCompleted is the event handler that will be executed once the camera task completes. The following code snippet shows the onCameraTaskCompleted handler code with its helper methods:

public void onCameraTaskCompleted(object sender, PhotoResult e)
{
    // ... Code is omitted for simplifying things ...    
    switch (e.TaskResult)
    {
        case TaskResult.OK:
            try
            {
                string imagePathOrContent = string.Empty;

                if (cameraOptions.DestinationType == FILE_URI)
                {
                    // Save image in media library
                    if (cameraOptions.SaveToPhotoAlbum)
                    {
                        MediaLibrary library = new MediaLibrary();
                        Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ...
                    }

                    int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto);
                    int newAngle = 0;
                
                    // ... Code is omitted for simplifying things ...

                    Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle);

                    // we should return stream position back after saving stream to media library
                    rotImageStream.Seek(0, SeekOrigin.Begin);

                    WriteableBitmap image = PictureDecoder.DecodeJpeg(rotImageStream);

                    imagePathOrContent = this.SaveImageToLocalStorage(image, Path.GetFileName(e.OriginalFileName));
                }
                else if (cameraOptions.DestinationType == DATA_URL)
                {
                    imagePathOrContent = this.GetImageContent(e.ChosenPhoto);
                }
                else
                {
                    // TODO: shouldn't this happen before we launch the camera-picker?
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType"));
                    return;
                }

                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));

            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image."));
            }
            break;
            
            // ... Code is omitted for simplifying things ...
    }
}

If the camera capture operation succeeds, then e.TaskResult == TaskResult.OK will be true, and if the user requires the result of the captured image as a Base-64 encoded string, then the captured image is retrieved and processed in the GetImageContent(stream) method. The GetImageContent(stream) function, which is shown in the following code snippet, converts the image to a Base-64 encoded string that is returned to the JavaScript Cordova client using the DispatchCommandResult() method. We will illustrate the DispatchCommandResult() method in more detail later on in this book.

If the user requires the result of the captured image as a file URI string, then the file URI of the image file is retrieved using the SaveImageToLocalStorage() method (whose implementation is shown in the following code snippet) and is then sent to the JavaScript Cordova client using DispatchCommandResult():

private string GetImageContent(Stream stream)
{
    int streamLength = (int)stream.Length;
    byte[] fileData = new byte[streamLength + 1];
    stream.Read(fileData, 0, streamLength);

    //use photo's actual width & height if user doesn't provide width & height
    if (cameraOptions.TargetWidth < 0 && cameraOptions.TargetHeight < 0)
    {
        stream.Close();
        return Convert.ToBase64String(fileData);
    }
    else
    {
        // resize photo
        byte[] resizedFile = ResizePhoto(stream, fileData);
        stream.Close();
        return Convert.ToBase64String(resizedFile);
    }
}

private string SaveImageToLocalStorage(WriteableBitmap image, string imageFileName)
{
    // ... Code is omitted for simplifying things ...
    var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
    if (!isoFile.DirectoryExists(isoFolder))
    {
        isoFile.CreateDirectory(isoFolder);
    }

    string filePath = System.IO.Path.Combine("///" + isoFolder + "/", imageFileName);

    using (var stream = isoFile.CreateFile(filePath))
    {
        // resize image if Height and Width defined via options 
        if (cameraOptions.TargetHeight > 0 && cameraOptions.TargetWidth > 0)
        {
            image.SaveJpeg(stream, cameraOptions.TargetWidth, cameraOptions.TargetHeight, 0, cameraOptions.Quality);
        }
        else
        {
            image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, cameraOptions.Quality);
        }
    }

    return new Uri(filePath, UriKind.Relative).ToString();
}

As you can see from the examples of Android and Windows Phone Platforms, in order to implement a photo capture using the device camera on two mobile platforms, we had to use two different programming languages and deal with totally different APIs. Thanks to Apache Cordova unified programming JavaScript interface, you don't even need to know how every mobile platform is handling the native stuff behind the scene, and you can only focus on implementing your cross-platform mobile application's business logic with a neat unified code base.

By now, you should have been comfortable with knowing and understanding the Apache Cordova architecture. In the upcoming chapters of this book, however, we will explain the bits of Apache Cordova in more detail, and you will acquire a deeper understanding of the Apache Cordova architecture by creating your own custom Cordova plugin in Chapter 6, Developing Custom Cordova Plugins.

 

Overview of Cordova APIs


Currently, Apache Cordova supports the following mobile native functions APIs:

  • Accelerometer: This allows you to capture the device motion in all directions (x, y, and z)

  • Camera: This allows you to use the default camera application in order to capture photos

  • Capture: This allows you to capture audio using the device's audio recording application, capture images using the device's camera application, and capture video using the device's video recording application

  • Compass: This allows you to get the direction that the device is pointing to

  • Connection: This provides you with the information about the device's cellular and Wi-Fi connection

  • Contacts: This allows you to access the device's contacts database, create new contacts in the contacts list, and query the existing device contacts list

  • Device: This allows you to get the hardware and software information of the device; for example, it allows you to get the device model, receive the platform and its version, and finally, receive the device name

  • Events: This allows you to listen and create handlers for Apache Cordova life cycle events. These life cycle events are as follows:

    • deviceready: This event fires once Apache Cordova is fully loaded

    • pause: This event fires if the application is put into the background

    • resume: This event fires if the application is resumed from the background

    • online: This event fires if the application becomes connected to the Internet

    • offline: This event fires if the application becomes disconnected from the Internet

    • backbutton: This event fires if the user clicks the device's back button (some mobile devices have a back button, such as Android and Windows Phone devices)

    • batterycritical: This event fires if the device's battery power reaches a critical state (that is, reaches the critical-level threshold)

    • batterylow: This event fires if the device battery power reaches the low-level threshold

    • batterystatus: This event fires if there is a change in the battery status

    • menubutton: This event fires if the user presses the device's menu button (the menu button is popular for Android and BlackBerry devices)

    • searchbutton: This event fires if the user presses the device's search button (the search button can be found in Android devices)

    • startcallbutton: This event fires when the user presses the start and end call buttons of the device

    • endcallbutton: This event fires when the user presses the start and end call buttons of the device

    • volumeupbutton: This event fires when the user presses the volume up and down buttons of the device

    • volumedownbutton: This event fires when the user presses the volume up and down buttons of the device

  • File: This allows you to process files (which is to read, write, and navigate filesystem directories), and it is based on the W3C file APIs

  • Geolocation: This allows you to receive the device's location using GPS or using network signals, and it is based on W3C geolocation APIs

  • Globalization: This allows you to get the user's locale and perform locale-specific operations

  • InAppBrowser: This represents a web browser view that is displayed when any call to window.open() or a link whose target is set to "_blank" is clicked

  • Media: This allows for the recording of audio files programmatically, without using the device default recording application, as well as playing audio files

  • Notification: This allows the display of audible notifications such as beeps, the display of tactile notifications such as vibrations, and displaying visual notifications such as the normal device visual messages to the user

  • Splashscreen: This allows you to display application splash screen

  • Storage: Apache Cordova provides the following storage capabilities:

    • Using the W3C web storage interface which is about LocalStorage and SessionStorage. It is important to know that local storage is a permanent storage that exists on your device even if your application is closed, while session storage is a temporary storage that is erased when the user session ends, which is when the application is closed.

    • Using the full features of relational databases by supporting Web SQL on almost all the platforms. For Windows Phone and Windows Platform, it supports IndexedDB, which is currently a W3C standard.

Tip

Although Web SQL is deprecated, it was and still is a powerful specification for creating and working with relational data.

All of these APIs will be illustrated in far more detail, along with examples, as you read this book. It is important to note that not all of these APIs are supported in all the platforms. You will be able to specifically check which ones are not supported in the following list. Also note that this list applies to Apache Cordova Version 3.4, and it might be changed later. The following table shows the unsupported APIs on the different platforms. Please note that X here means unsupported:

 

Firefox OS

Tizen

Windows 8

Blackberry 10

Capture API

X

X

X

 

Compass

X

   

Connection

X

   

Contacts

 

X

X

 

Events

X

   

File

X

X

  

Globalization

X

X

X

X

InAppBrowser

X

X

  

Media

X

   

Notification

X

   

Splashscreen

X

X

  

Storage

X

   
 

Summary


In this chapter, you have been given a powerful introduction to Apache Cordova. You now know what Apache Cordova is, and understand the current challenges of today's mobile development and how it can reduce the complexities of these challenges. You should now understand the differences between mobile web, hybrid mobile, and native mobile applications. You should also know the architecture of Cordova and how it works behind the scenes with an example of a photo capture using a camera. Finally, you have an overview of Apache Cordova APIs and what every API does from a high-level point of view.

In the next chapter, you will start the real work with Apache Cordova by developing your first Apache Cordova application from scratch.

About the Authors
  • Hazem Ahmed Saleh Ahmed

    Hazem Saleh has 10 years of experience in Java EE, mobile, and open source technologies. He has worked as a technical consultant for many clients in Europe (Sweden), North America (USA and Canada), South America (Peru), Africa (Egypt, Morocco, and Zambia), and Asia (Qatar, Kuwait, and KSA). He is an Apache committer and a person who has spent many years of his life writing open source software. Besides being the author of JavaScript Unit Testing, Packt Publishing, and Pro JSF and HTML5: Building Rich Internet Components, Apress, and the co-author of The Definitive Guide to Apache MyFaces and Facelets, Apress, he has also authored many technical articles. He is also a contributing author recognized by developerWorks and a technical speaker at both local and international conferences such as ApacheCon in North America, GeeCon, JSFDays, CONFESS in Vienna, and JavaOne in San Francisco, Moscow, and Shanghai. Hazem is now working for IBM Egypt as an advisory software engineer. He is a member of the IBM Mobile Global Center of Competency (CoC) and an IBM Certified Expert IT specialist (L2).

    Browse publications by this author
  • Hazem Saleh

    Hazem Saleh has 10 years of experience in Java EE, mobile, and open source technologies. He has worked as a technical consultant for many clients in Europe (Sweden), North America (USA and Canada), South America (Peru), Africa (Egypt, Morocco, and Zambia), and Asia (Qatar, Kuwait, and KSA). He is an Apache committer and a person who has spent many years of his life writing open source software. Besides being the author of JavaScript Unit Testing, Packt Publishing, and Pro JSF and HTML5: Building Rich Internet Components, Apress, and the co-author of The Definitive Guide to Apache MyFaces and Facelets, Apress, he has also authored many technical articles. He is also a contributing author recognized by developerWorks and a technical speaker at both local and international conferences such as ApacheCon in North America, GeeCon, JSFDays, CONFESS in Vienna, and JavaOne in San Francisco, Moscow, and Shanghai. Hazem is now working for IBM Egypt as an advisory software engineer. He is a member of the IBM Mobile Global Center of Competency (CoC) and an IBM Certified Expert IT specialist (L2).

    Browse publications by this author
Latest Reviews (1 reviews total)
Γενικά βιβλίο χρήσιμο χωρίς να ξεχωρίζει ιδιαίτερα σε σχέση με αλλά ίδιου θέματος. Πολύ θετικό στοιχείο είναι ο τρόπος οργάνωσης των πληροφοριών.
JavaScript Mobile Application Development
Unlock this book and the full library FREE for 7 days
Start now