Tuesday, January 31, 2012

Android: Getting Started with PhoneGap

Android: Getting Started with PhoneGap

PhoneGap is a platform for creating native mobile phone applications using HTML 5.

HTML 5 is a powerful new specification that goes well beyond the capabilities of traditional HTML. APIs that are new in HTML 5.
  • Canvas: 2d drawing
  • Offline Web Applications
  • Document Editing
  • Drag and Drop
  • Cross Document Messaging
  • Browser History Management
  • Web Storage (Stores large amounts of data better than Cookies)
  • Geolocation
  • Indexed DB
  • ...
However, HTML 5 alone is not enough for delivering portable mobile phone applications. For instance, it does not contain many of the APIs needed to access the sensors on your phone: Compass, Barometer, Proximity and others. It does not provide access to the event data that you may need: battery level, connection status and other events. It certainly doesn't provide you with access to platform specific features such as Android notifications.

Enter PhoneGap, it is the middle layer that sits between the native platform and HTML 5. There is nothing magic about PhoneGap. You can certainly implement HTML 5 applications on Android without it. But it makes HTML 5 development more convenient for you:
  1. It sets up a managed WebView so there is no need to do this manually. When implementing a PhoneGap application you start thinking about HTML immediately rather than having to deal with setting up the native portion of the application -> Delclaring a WebView layout, Setting it as the content view, etc.
  2. It handles accessing native APIs for you. Without phoneGap, you would need to write code like: WebView.addJavaScriptInterface(new BarometerReader(), "barometer");
The second point is by far the most important. By providing Javascript APIs for accessing native data, PhoneGap can insure that your Javascript is the same on every platform. It eliminates the small percentage of Javascript code that would need to be rewritten for each platform. The PhoneGap APIs are located here:
http://docs.phonegap.com/en/1.4.0/phonegap_notification_notification.md.html#Notification

They include support for:
  • Accelerometer
  • Camera
  • Capture
  • Compass
  • Connection
  • Contacts
  • Device
  • Events
  • Geolocation
  • Media
  • Notification
  • Storage
Let's look at very simple example:

index.html:


<!DOCTYPE html>
<html>
<head>
    <title>Device Properties Example</title>


    <script type="text/javascript" charset="utf-8">


    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);


     // PhoneGap is ready
     function onDeviceReady() {
        var element = document.getElementById('deviceProperties');


        element.innerHTML = 'Device Name: '     + device.name     + '<br />' + 
                            'Device PhoneGap: ' + device.phonegap + '<br />' + 
                            'Device Platform: ' + device.platform + '<br />' + 
                            'Device UUID: '     + device.uuid     + '<br />' + 
                            'Device Version: '  + device.version  + '<br />';
    }
    </script>
</head>
<body>

    <h1>Let's print some device info</h1>

    <p id="deviceProperties">Loading device properties...</p>

    <h2>Done</h2>

</body>
</html>


HelloPhoneGapActivity.java:


import com.phonegap.*;
import android.os.Bundle;
public class HelloPhoneGapActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

The output on my HTC Desire looks as follows:


In a nutshell, instead of overriding Activity we now override 'DroidGap' which is provided by the PhoneGap jar library. In onCreate, instead of calling setContentView, we call super.LoadUrl with our index.html file. The full installation and start-up details are located here:

Don't worry, PhoneGap is very easy to set up. The one gotcha is to make sure the following line is correct:
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

In the most recent distributions of the PhoneGap, the script name is slightly different than "phonegap.js". It may be something like: phonegap-1.3.0.js. Ensure this file name correctly refers to the javascript file in your project or onDeviceReady() will not be called.

Is PhoneGap ready for large scale projects? I have my concerns...The code above is the simplest of examples yet it has not managed to correctly print my device name. The device is a HTC desire not a 'htc_bravo' which can be verified on the 'Phone Identity' screen. I suspect it doesn't parse correctly due to the unorthodox string returned by the native API "htc_htc_desire". 


I've had feedback from other consultants that have abandoned PhoneGap due to portability issues. I've been told in generally works fine for iPhone and was getting better on Android, but didn't work as well on the smaller platforms like winPhone, BlackBerry, Symbian and others.


In conclusion, you should consider using a platform like PhoneGap to access phone specific features through a standardized API. There are other platforms that can be used to accomplish the same goal: Titanium, JQTouch and Sensha Touch for example. However due to the immaturity of these platforms, you should make sure they are capable of reliably delivering the APIs you need for the mobile platforms that you are targeting.


Glen Cook
eWhiz Mobile

Sources:
http://en.wikipedia.org/wiki/HTML5
http://phonegap.com/
Chris Woods
Martin Lewin

Tuesday, January 17, 2012

Android: Native or HTML 5 Applications


The biggest mistake made by companies in today's mobile environment is writing native applications when using HTML 5 would be more appropriate.

What is HTML 5? Broadly speaking, it includes the technologies for: HTML mark-up, Javascript and Cascading Style Sheets. It includes support for amongst other technologies: geo-location, audio & video, web storage, multi-touch, device orientation, speech recognition,  and the Javascript equivalent of threads: web workers. As you can see, HTML 5 goes well beyond the capabilities of earlier web technologies.

Using HTML 5 reduces the cost of development and expands the reach of the application. By doing an Android application in HTML 5, it only requires minor tweaks to bring it to iPhone, WinPhone and other platforms.

What is the case for doing native applications? Given that we can reach many more devices by using HTML 5, we should consider the justifications:
  • Broader access to the underlying hardware and sensors
    • Camera
    • Barometer
  • Tighter integration with system features: 
    • Notifications
    • Home Screen Widgets
  • Ability to integrate with other applications 
    • Launch the native Facebook application
    • Use the Android software bus (Intents) to pass it data
  • Faster, smoother and can be more attractive
  • More explicit management of resources
    • Battery
    • Memory
  • First access to new features not yet accessible through HTML 5
  • Achieving a native look and feel
  • Access to advanced UI components
    • Renderscript: 3D views utilizing hardware acceleration
      • The You Tube application's wall of videos
      • The playlist carousel used in the standard Honeycomb media player
    • Other views that have no HTML 5 equivalent: StackView for example 
An attractive alternative is to create a hybrid application. This is accomplished by embedding a web view inside a native application. Android provides excellent facilities for passing data between the native and HTML 5 portions of the application. For example, you can use WebView.loadUrl from the SDK to evaluate Javascript within a web page and return the results for parsing and further processing. In the opposite direction, Javascript can talk to native components using the WebView's  Javascript interface. For example:
WebView.addJavaScriptInterface(new BarometerReader(), "barometer");
Hybrid applications are more discoverable than pure web applications. Web applications can made available through the Chrome Web Store which is analogous to the Android Store. See the following screenshot of a Chrome browser with Angry Birds installed from the Chrome Web Store:


While this is great, it suffers from several issues:
  • Chrome has not yet been ported to Android
  • There is no section in the Android Market for web applications -> No equivalent of the Chrome Application Store
  • Creating a pure web application does not allow for a home screen launch icon on your mobile device
I imagine the Chrome Web Store will eventually be integrated into the Android Market in such a way that the user will not need to initially know if an application is native or pure HTML 5. But at the moment, it makes sense to create hybrid applications if for no other reason than they are more discoverable. By hybrid, we mean at a minimum embedding a web view inside of a native Dalvik application.

In conclusion, companies should be looking at writing Hybrid applications using HTML 5 to broaden their reach and to utilize the existing skills that exist within their organisations. This is especially true if the application in question is primarily a content application such as a newspaper or magazine. HTML 5 is the future and will increasing replace native applications written for specific platforms.

Glen Cook
Consultant at eWhizMobile


Sources:
Android: Native vs. HTML 5 Applications
Introduction to HTML 5
SDK Documentation: WebView