Mobile application with PhoneGap

Author: Eugeniy Marilev
Date of publication: 2014-05-06 10:47:19
Phonegap - a free cross-platform library for mobile platforms, that allows to display Web pages using HTML5, CSS3, JavaScript. It allows you to run the same application on different mobile devices. Until recently, there have been open PhoneGap source, but as usually happens - the development was bought, and soon was transferred to the fund Apache. Fortunately, the library already has a large number of plug-ins written by third parties, which greatly simplify the development of cross-platform applications for mobile devices. Download plug-ins PhoneGap here. A widespread misconception of beginners is that PhoneGap converts HTML, CSS code and Javascript pages in native-code applications for the platform (Android, iOS, Windows Mobile, etc.). In fact, the mapping of HTML + CSS is loaded by the page content into a special WebView. This also has an advanced webView JavaScript engine (typically used by WebKit), which is doing its job better than a standard browser. The library consists of two interrelated parts:
  1. Native wrapper - a wrapper features a particular platform as a set of classes. The interface of the library classes is the same for all platforms. Currently PhoneGap wrapper allows you to work with the following resources and devices: compass, accelerometer, video-camera. file system, network connection, geolocation, notification repository (database). For more details, please, see the documentation.
  2. Javascript wrapper - a wrapper for a native wrapper via Javascript. Yes, exactly this way. In fact, when you call the JavaScript functions wrapper client script refers to the Native wrapper functions by:
    PhoneGap.exec = function(success, fail, service, action, args) { … }
    
In order to provide the full cross-platform code in javasript of the product, we also need the following libraries: jQuery, jQuery Mobile, jTemplates and, if needed, jQuery UI (although I would not recommend it as much due to overusing resources, what is very critical for low-power devices). jQuery Mobile has now begun to develop in the direction of closer integration with PhoneGap, that is really good (http://jquerymobile.com/demos/1.0/docs/pages/phonegap.html). So, now you're ready and you can start developing your first application using PhoneGap on JQuery Mobile. But in order to prevent mistakes, we will make an application once optimized for mobile devices:
<!DOCTYPE html> 
<html> 
        <head> 
        <title>PhoneGap Mobile application</title> 
        <meta name="viewport" content="width=device-width, initial-scale=1"> 
        <link rel="stylesheet" href="jquery.mobile-1.0.min.css" />
        <script type="text/javascript" src="jquery-1.6.4.min.js"></script>
        <script type="text/javascript" src="jquery.mobile-1.0.min.js"></script>
        <script type="text/javascript">
        $('#main_page').live('pageshow', function(event) {
                var options = {
                        url: '/records/list', //удаленный ресурс, отдающий данные списка в формате json
                        success: function(data) {
                                var view = $('#listview_test');
                                var template = view.find('.template'); //получение шаблона элементов
                                var items =  view.find('.items'); //получение контейнера елементов
                                items.setTemplateElement(template); //установка шаблона элементов
                                items.processTemplate(data); //отображение полученных данных в виде списка элементов по шаблону
                                view.listview('refresh'); //обновление jQueryMobile списка элементов
                                $.mobile.hidePageLoadingMsg();
                        },
                        error: function(jqXHR) {
                                $.mobile.hidePageLoadingMsg();
                                console.log(jqXHR.responseText);
                        },
                        dataType: 'json'
                };
                $.mobile.showPageLoadingMsg();
                $.ajax(options);
        });
       </script>
</head> 
<body> 
 
<div id="main_page"  data-role="page">
        <div data-role="header">
                <h1>My Page</h1>
        </div><!-- /header -->
        <div data-role="content"> 
                <p>Dynamic list sample</p> 
           <ul data-role="listview" id="listview_test">
                <textarea class="template" style="display:none;">
                {#foreach $T as record}
                <li class="ui-li-has-thumb" data-theme="c">
 
                                        <a href="/object/view/id/{$T.record.id}" class="ui-link-inherit option-link">
                                        <img src="{$T.record.logo}" class="ui-li-thumb" />
                                        <h3 class="ui-li-heading">{$T.record.name}</h3>
                                        </a>
                             </li>
                             {#/for}
                </textarea>
                <div class="items"></div>
           </ul>             
        </div><!-- /content -->
</div><!-- /page -->
</body>
</html>
Although, jQuery Mobile in their documentation provides examples of dynamically loadable pages, in which the entire content of the page is loaded from the server, there are a number of arguments that prove the distinct advantage of the previously described method of loading the page:
  1. Page that is entirely loaded is larger compared to the template page. And as a page template in the case of PhoneGap is stored on the client, it becomes clear which traffic is better economically-wise.
  2. The remote server does not deal with output html, and only loads the data and formats them into json, thus ensuring a fast loading of the page content comparing to the html-version of the finished layout. Also the download speed, of course, saves the server resource, as a memory.
Moreover, I want to mention another factor that plays an important role in the choice of my way to template pages. It was impossible to foresee, that's why I warn you not to do the same mistakes as I did. There are many examples of work of the binder PhoneGap, jQuery Mobile, where all the HTML, CSS, JavaScript are requested from the server, and native-application contains the following line of code:
package com.myapp;
 
import android.os.Bundle;
 
public class MyApplication extends AdpoiDroidGap {      
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("http://myapp.com");
    }
}
There are no doubts that it is very convenient to write the application like this, it is simply to style it in order to make it display perfectly in the browser on your mobile phone and then make a native of a mobile application — it takes a minute. But there are some mobile platforms like Windows Phone 7, wherein:
  1. Implementation of PhoneGap does not support option $.support.cors and $.mobile.allowCrossDomainPages, that means that the pages from a remote host are not loaded. A similar behavior of the function $.ajax is noticed in the browsers IE, including IE9, which is likely the root of the problem.
  2. When the page loads the application from a remote host PhoneGap does not work at all, even the notification.alert. In addition to the problems above the process of downloading the application from a remote host to the local load is rather slow, which is a very important factor for mobile platforms. Therefore, the line:
super.loadUrl("http://myapp.com");
Change to:
super.loadUrl("file:///android_asset/www/index.html");
And include all client scripts and layouts in the package with the application. As data is loaded from a remote server (cross domain AJAX request), it is easily implemented using a flag dataType: 'jsonp' calls for jQuery.ajax. I hope my experience in these technologies will be useful for you. A good luck with PhoneGap!
Article comments
Comments:
Василий
19\02\2012
Крутая статья))
Azamat
31\05\2012
Да, действительно неплохо все разжевано, спасибо. Однако возможно вы поможете пояснить такой момент: я не совсем понял что именно платно, а что бесплатно в PhoneGap. Сам фреймворк, как я понимаю, бесплатен. И его можно использовать для самостоятельной компиляции в интересующую платформу. Но надо самому соотвествующие IDE ставить. А платен компилирующий сервер PhoneGap Build (который использовать не обязательно). Так получается? И не понятно, что там с перепродажами не станет ли Apache денег требовать в будущем. А то потом начатые проекты придется переписывать ) А также вы не в курсе, проходят ли такие приложения в AppStore ? Вроде говорят сейчас помягче стало, к самому js+html претензий нет.
djvibegga_admin
31\05\2012
PhoneGap пока абсолютно бесплатен. Я не думаю, что Apache сделает из него что-то настолько крутое, чтобы брать за это деньги, а если сделает - сделают fork на PhoneGap). Приложения на AppStore с использованием PhoneGap выложить у вас получить, главное иметь лицензию на разработку ПО, и компиливать в лиценционном MacOSX.
Only logged users can leave comments.