Introducing app-UI

Posted: April 24th, 2012 | Author: | Filed under: Android, Apps, Cordova, Development, HTML5, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , , , , , , | 9 Comments »

I’d like to take a moment and introduce app-UI, a new open source application framework that I’ve been working on.

app-UI is a collection of reusable “application container” user interface components that may be helpful to web and mobile developers for creating interactive applications using HTML and JavaScript, especially those targeting mobile devices. app-UI is a continual work in progress – it was born out of the necessity to have rich & native-feeling interfaces in HTML/JS experiences, and it works great with PhoneGap applications (http://www.phonegap.com). app-UI can easily be styled/customized using CSS.

Disclaimer: Please keep in mind that things will change as the project is improved and matured – this is a beta/early prototype.

All of app-UI was created using HTML, CSS, & JavaScript. All animations are rendered using CSS3 translate3d, so that they are hardware accelerated (where supported). app-UI works well on iOS, Android and BlackBerry browsers (others not tested), and works well on the latest releases of most desktop browsers (I know it does not work on old versions of IE).


Why?

You might be wondering “why create this?” when there are other open source alternatives like jQuery Mobile. The primary motivation for creating app-UI was to have reusable application containers that are highly performant, and do not force any prescriptive development paradigms. With respect to animations/transitions, app-UI outperforms the alternatives, particularly on mobile devices.

app-UI can be used with many different existing frameworks – app-UI only requires jQuery as a solution accelerator framework. It will work with existing UI widget frameworks (jQuery UI, Twitter Bootstrap, etc…), and will work with existing templating frameworks (Moustache, Knockout, Handlebars, etc…).


Application Containers

app-UI currently has three application containers, and at this time it is not intended to be a complete UI widget framework.

Please see the “samples” directory for usage scenarios – there is no documentation yet.

ViewNavigator

The ViewNavigator component allows you to create mobile experiences with an easily recognizable mobile UI paradigm. You use this to push & pop views from the stack.

Samples:

SplitViewNavigator

The SplitViewNavigator component allows you to create tablet experiences with an easily recognizable mobile UI paradigm. The SplitViewNavigator allows you to have side-by-side content in the landscape orientation, and the sidebar is hidden in portrait orientation.

Samples:

SlidingView

The SlidingView allows content to slide to the side using a horizontal swipe gesture, revealing a navigation container “underneath”. This is very similar to the behavior in Facebook’s iPad application.

Samples:

Just swipe horizontally with a finger or the mouse…


Bugs & Features

No software is ever bug-free. If you encounter an issue, have feedback, or have feature requests, please log them at: https://github.com/triceam/app-UI/issues

-OR-

Fork it, fix it, and send me a pull request.

Please do not just complain.


Real World Usage

You can see this framework in the following real-world apps:

If you have built your own app using this framework, please let me know! (@andytrice on twitter)


Download

Get started with app-UI today! Just browse to http://triceam.github.com/app-UI/, read the details, download a copy, and start building your own apps!

If you’re building something cool with it, then let me know! I’d love to hear about it.


Welcome Appliness!

Posted: March 28th, 2012 | Author: | Filed under: Adobe, Android, Apps, Development, Digital Publishing, HTML5, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , , , , , , | No Comments »

Appliness is a new digital magazine and the first of it’s kind to focus entirely on web application development!   Appliness was created entirely using Adobe Digital Publishing Suite, and the effort was lead by our own Michael Chaize.   Go download a copy today!  It’s also FREE!

 

Be sure to also check out how this magazine was created using Adobes Digital Publishing Suite, and check out the video preview above. Interested in contributing in Appliness or providing us with valuable feedback? If so, you’re in luck–let us know here: http://appliness.com/give-us-feedback/. We’d love to hear from you!


Who Uses PhoneGap/Apache Cordova?

Posted: March 27th, 2012 | Author: | Filed under: Adobe, Android, Apps, Cordova, Development, HTML5, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , , , | 3 Comments »

I see questions and comments all the time with the general sentiment “it looks nice, but who really uses PhoneGap/Apache Cordova?”. There is no way to create a definitive list of everyone who uses it, but the general answer is “more people than you think”. Here are a few organizations that you might recognize who are using either PhoneGap or Apache Cordova in their cross-platform mobile solutions and/or tools. (PhoneGap is a distribution of Apache Cordova)

Wikipedia

The official Wikipedia mobile application is built using PhoneGap.   This is currently available for Android and BlackBerry, and it is my understanding that the PhoneGap codebase will be deployed for iOS soon.  This project is open source, and the full source code is available on GitHub at https://github.com/wikimedia/WikipediaMobile

You can read more about this application on the PhoneGap Showcase.

Facebook

Facebook uses a forked version of Apache Cordova in their mobile SDK.   You can learn more about Facebook’s mobile SDK at https://developers.facebook.com/docs/guides/mobile/, and check out some of the showcase apps that developers have built on top of the Facebook mobile experience at https://developers.facebook.com/showcase/mobile/.

Salesforce

Salesforce uses a fork of Apache Cordova for their mobile development SDK.  The forked version of their SDK is included within both their iOS and Android SDK repositories on GitHub (inside of the “external” sub directories).

IBM

IBM recently acquired Worklight, who provides a platform for developing mobile applications.  IBM/Worklight’s mobile application development platform is built on top of PhoneGap.   IBM is also heavily involved with core Apache Cordova development (see the list of committers).

Microsoft

Microsoft is involved with core Apache Cordova development (specifically for the Windows Phone platform).   Not only are staff from Microsoft committers for the core Apache Cordova project, Microsoft has also used PhoneGap on public mobile applications that target multiple platforms.   This includes the XBox-Live integrated gaming application Halo Waypoint, for both iOS and Android.  Check out Halo Waypoint in the video below, it looks awesome:

(The license under “about” inside Halo Waypoint clearly has a reference to PhoneGap).

Adobe

I think most people already know how deeply involved Adobe is with PhoneGap, but I’ll try to recap quickly…  In late 2011, Adobe acquired Nitobi, the creators of PhoneGap, and contributed PhoneGap to the Apache Software Foundation as the Apache Cordova project.   Adobe has resources dedicated to furthering PhoneGap and is dedicated to the success of the platform.   Not only are we helping develop and mature PhoneGap/Apache Cordova, we also build some of our own applications with it.   (Maybe I’ll be able to talk about those some day.)

RIM

Research in Motion (RIM), the company behind the BlackBerry platform not only developed the core PhoneGap/Cordova API for BlackBerry Playbook devices, but also is heavily involved in Cordova-JS development, and has integrated PhoneGap/Cordova support in the Ripple device emulator.  (Note: The BlackBerry smartphone implementation was pre-existing and was implemented by IBM and Nitobi.)

Zynga

Zynga, one of the largest gaming companies, uses PhoneGap and HTML5 to build awesome games.  For example, the popular Mafia Wars title is built using PhoneGap.

Logitech

Logitech used PhoneGap to develop the Logitech Squeezebox Controller application, which uses your home wifi connection to control a Squeezebox Internet radio device from your smart phone.   You can read more about this application on the PhoneGap application showcase, or download it now for iOS or Android.

Still not sure if anyone uses PhoneGap? What about these, among many others?

Alcatel-Lucent      Deutshce Telecom      Ars Technica      Sabre
Cisco Systems      Time Warner      The Onion

Additional sources: ReadWriteWeb, slideshare

Go check out the PhoneGap app showcase to see even more: http://phonegap.com/apps


PhoneGap Explained Visually

Posted: March 22nd, 2012 | Author: | Filed under: Adobe, Android, Cordova, Development, HTML5, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , , , , , , | 6 Comments »

I’ve been “out and about” lately, attending tech conferences, meetup groups, and meeting with developers in their offices, and I am getting great feedback on mobile development and PhoneGap. There are some common questions that I am often asked, and I hope this post helps everyone understand PhoneGap better.

PhoneGap

Before I go too far, let me attempt to clearly state what PhoneGap is… PhoneGap is an application container technology that allows you to create natively-installed applications for mobile devices using HTML, CSS, and JavaScript.   The core engine for PhoneGap is also 100% open source, under the Apache Cordova project.  You can read more about PhoneGap under my “What is PhoneGap?” & Other Common Questions post.


PhoneGap User Interface

The user interface for PhoneGap applications is created using HTML, CSS, and JavaScript.  The UI layer of a PhoneGap application is a web browser view that takes up 100% of the device width and 100% of the device height.

Think of this as a “headless” web browser.  It renders HTML content, without the “chrome” or window decoration of a regular web browser.  You build your application to take advantage of this space, and you build navigational/interactive/content elements and application chrome into your HTML and CSS based user interface.

The web view used by PhoneGap is the same web view used by the native operating system.   On iOS, this is the Objective-C UIWebView class; on Android, this is android.webkit.WebView.  Since there are differences in the web view rendering engines between operating systems, make sure that you account for this in your UI implementation.


PhoneGap API

PhoneGap provides an application programming interface (API) that enables you to access native operating system functionality using JavaScript. You build your application logic using JavaScript, and the PhoneGap API handles communication with the native operating system.

You can read about the PhoneGap API and all of the native functionality it exposes at docs.phonegap.com.

In addition to the “out of the box” functionality, you can also leverage PhoneGap’s JavaScript-to-native communication mechanism to write “native plugins”. PhoneGap native plugins enable you to write your own custom native classes and corresponding JavaScript interfaces for use within your PhoneGap applications.  You can read more about PhoneGap native plugins at: http://www.tricedesigns.com/2012/03/01/phonegap-native-plugins/ and http://wiki.phonegap.com/w/page/36752779/PhoneGap%20Plugins


PhoneGap Application Packaging and Distribution

PhoneGap applications are developed using HTML, CSS, and JavaScript, however the final product of a PhoneGap application is a binary application archive that can be distributed through standard application ecosystems.

For iOS applications the output is an IPA file (iOS Application Archive), for Android applications the output is an APK file (Android Package), for Window Phone the output is a XAP file (Application Package), etc…  These are the same application packaging formats used by “native” applications, and can be distributed through the appropriate ecosystems (iTunes Store, Android Market, Amazon Market, BlackBerry App World, Windows Phone Marketplace, etc…)


PhoneGap High-Level Application Architecture

Specific application architectures are going to differ on a case-by-case basis, however most data-driven applications employ the following basic architecture.   The PhoneGap application acts as a client for the user to interact with.   The PhoneGap client communicates with an application server to receive data.   The application server handles business logic and communicates with a back-end data repository.

The application server is normally a web server (Apache, IIS, etc…) and has a server side scripting language such as ColdFusion, Java, .NET, PHP, etc… PhoneGap is agnostic of back-end technologies and can work with any application server using standard web protocols.   The application server performs business logic and calculations, and generally retrieves or persists data from a separate data repository – this is normally a relational database, but could be any structure or mechanism for data persistence.

PhoneGap applications generally do not talk directly to a database; communication is routed through an application server.    The client to application server communication can be based upon standard HTTP requests for HTML content, REST-ful XML services, JSON services, or SOAP (or websockets if your OS supports it).  These are the exact same techniques that you would use in a desktop-browser based AJAX application.

The client-side architecture generally uses the single-page application model, where the application logic is inside a single HTML page.  This page is never unloaded from memory.  All data will be displayed by updating the HTML DOM, data is retrieved from the application server using AJAX techniques, and variables are kept in-memory within JavaScript.

Multi-page client-side application architectures are supported, but are not recommended because you lose in-memory variables when loading a separate page.


Changes with PhoneGap 1.5

Posted: March 21st, 2012 | Author: | Filed under: Adobe, Android, Cordova, Development, HTML5, iOS, Mobile, open source, PhoneGap | Tags: , , , , , , , , | 3 Comments »

Earlier this month, PhoneGap 1.5 was released.   There were a lot of enhancements in this release.  However, if you’ve tried to update an existing codebase from PhoneGap 1.4 to 1.5, you may have realized that things look a bit different.   Basically, the entire PhoneGap codebase has migrated from PhoneGap naming to Apache Cordova naming conventions.

Every reference to “PhoneGap” is now “Cordova”.  This includes, but is not necessarily limited to:

  • phonegap.js is now cordova.js
  • The “PhoneGap” object in JavaScript is now “Cordova” – this means every reference to “PhoneGap” should now reference “Cordova”
  • In native code, every PhoneGap class that was prefixed with “PG” is now prefixed with “CDV”; for example, “PGPlugin” is now “CDVPlugin”
  • Documentation that refers to the PhoneGap class may be out of date… just switch the name reference.
  • The “PhoneGap” project template in Xcode is now “Cordova”

This is just a naming convention change as the PhoneGap project is moving to its new identity as Apache Cordova.  However, it is just a name.  Be sure to read this article from the PhoneGap team to understand why the name changed and to understand the relationship between “PhoneGap” and “Cordova”.

As a PhoneGap developer, how you build applications has not changed, and the power of PhoneGap/Cordova has not changed.   You can still create awesome apps with it, and it is still 100% open source.

If you are looking at code that doesn’t work in PhoneGap 1.5, then chances are you need to update to use the new naming conventions.

If you are just getting started, be sure to check out my “Getting Started with PhoneGap” guides on Adobe Developer Connection for both Android and iOS - both of these articles use the new naming conventions.


Welcome, Adobe Shadow!

Posted: March 7th, 2012 | Author: | Filed under: Adobe, Android, HTML5, iOS, Mobile | Tags: , , , , , , | 1 Comment »

Ready for the new era in multi-screen development?

Available now on labs.adobe.com, Adobe Shadow is a new, free tool that enables synchronized browsing and remote inspection across desktop and mobile experiences, in real time.

Rather than having me try to describe it, check out this video from Adobe TV…

From Adobe Labs:

Adobe® Shadow is a new inspection and preview tool that allows front-end web developers and designers to work faster and more efficiently by streamlining the preview process, making it easier to customize websites for mobile devices.

Shadow will be updated regularly to stay ahead of web standards, web browser updates and support for new mobile devices entering the market, while incorporating user feedback to provide the best functionality and experience possible.

This version of Shadow focuses primarily on the following:

  • Device pairing
  • Synchronized browsing and refreshing in sync with your computer
  • Perform remote inspection and debugging so you can see HTML/CSS/JavaScript changes instantly on your device.

Be sure to keep up with the latest and greatest information on Adobe Shadow:

Of course, don’t forget to go download Adobe Shadow and get started today (it’s free)!


Tricks for Debugging PhoneGap Applications in Desktop Browsers

Posted: March 2nd, 2012 | Author: | Filed under: Desktop, HTML5, JavaScript, Mobile, PhoneGap | Tags: , , , , | 1 Comment »

I often encourage people to develop as much as possible in desktop browsers when they are building PhoneGap applications.  While there are remote debugging tools such as weinre for remote debugging on devices, the developer experience is still better inside of a desktop browser because it gives you breakpoints and memory inspection capabilities.  In most cases, you can develop the vast majority of your application within the desktop browser, and switch to a physical device when integrating with PhoneGap APIs or for performance testing. Personally, I use Chrome, and take advantage of the Chrome Developer Tools.

However, when developing from the local file system, you will run into a few roadblocks with desktop browsers.  A big issue is the browser security model.  If you try to asynchronusly request files when the application is loaded from the local file system, you’ll like get an error like:

XMLHttpRequest cannot load (filename or url). Origin null is not allowed by Access-Control-Allow-Origin.

Luckily, there are a few tricks you can use to get around this… local HTTP servers and relaxing the browser’s security.  Note: I’m on a Mac, and I don’t know the syntax for these on Windows.

Local HTTP Server

The first option is to use a local web server to host files.   You can fire up a simple HTTP server from any directory in OSX by opening a terminal and using the following command:

python -m SimpleHTTPServer 8000

An HTTP server will start, and you’ll be able to access any content from that directory and child directories from the URL http://localhost:8000/  Thanks to @mesh for this trick.

However, this will only work for static content that is within your directory structure.   If you need dynamic content, you’ll need some sort of application server infrastructure.

Relaxed Browser Security

OK, that’s great, but it doesn’t cover every situation.   What if you don’t want a local application server configuration?  What if you want to develop against services that are remote, and you don’t control them?    Well, you are in luck.

You can disable security restrictions in Chrome to allow you to access these services.   The following command will allow unrestricted access from the file system, and will also allow cross-site requests.   Kill Chrome, then relaunch from a terminal window with the following flags:

open -a /Applications/Google\ Chrome.app --args --allow-file-access-from-files --disable-web-security

Using this configuration, you’ll be able to open an HTML file from the local file system, and that file will be able to make requests to other sites to access data or other resources.

In the screenshot below, you can see that I launched my Census Browser application from the local file system, and it can access services from http://www.tricedesigns.com.   With the default browser security policy, this would not be possible.

Local Application Debugging With Remote Services

WARNING: ONLY USE THIS FOR DEBUGGING!

Do not use this configuration for normal web browsing because it will leave your browser security wide open, and able to be exploited and compromised.  Do not browse the web when you’ve relaxed the security policy.

Thanks to fellow Adobe evangelist Piotr Walczyszyn for introducing me to this trick.


Pushing Data to a PhoneGap Web View

Posted: March 1st, 2012 | Author: | Filed under: HTML5, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , | 1 Comment »

UPDATE:

In PhoneGap 1.5, the naming conventions were changed to use the Apache Cordova naming conventions.   EX: PGPlugin is now CDVPlugin, phonegap.js is now cordova.js, etc…   If you are running into issues, please be sure to check the PhoneGap version and appropriate naming conventions.

ORIGINAL POST:

In my last post, which gave a crash course in PhoneGap Native Plugins, I discussed a scenario where you could use a native plugin and the writeJavascript function to “push” data into the UI/web view layer from the native code layer.   To elaborate on this scenario, I put together a sample application that demonstrates this concept in action.

I set up the sample application so that there is an extremely basic HTML user interface.   In that user interface, you can click a link which executes native code to start a timer (in the native code layer).   Once the timer is started, the user interface will be updated with a “started” message, and on every timer event, the user interface will be updated with the current time, as it is provided by the native code layer.   In this case, I am using a timer to simulate an external thread of execution, or stream of input from some other source (device or stream).   Take a look at the video below to see it in action:

Next, let’s examine how it works.

The HTML interface is very simple.   There is an <a> link, which calls the “doStart()” JavaScript function, an <h4> element to display status, and an <h2> element to display the content received from the native code layer. When the “doStart()” function is invoked, it calls the SamplePlugin JavaScript class’ “start()” function, passing a reference to the “successCallback()” function, which will get executed when a callback is received from the native layer.   The “updateContent()” function will just set the innerHTML value of the “output” element to the value passed as a parameter.

<!DOCTYPE html>
<html>
  <head>
  <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
	<meta charset="utf-8">

    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <script type="text/javascript" charset="utf-8" src="SamplePlugin.js"></script>
    <script type="text/javascript">

    function doStart() {
        SamplePlugin.start( successCallback );
    }

    function successCallback() {
        document.getElementById( "status" ).innerHTML = "started";
    }

    function updateContent( data ) {

        document.getElementById( "output" ).innerHTML = data;
    }

    </script>
  </head>
  <body onload="onBodyLoad()">
	<h1>Hey, it's PhoneGap!</h1>
	<a href="javascript:doStart()">Start!</a>

    <h4 id="status"></h4>
    <h2 id="output"></h2>
  </body>
</html>

In the SamplePlugin.js file, which is the JavaScript component of the native plugin, you can see that there is a SamplePlugin class instance that has a “start()” function.   The “start()” function invokes the PhoneGap.exec() command to invoke native code.

var SamplePlugin = {
    start: function (success, fail) {
        return PhoneGap.exec(success, fail, "SamplePlugin", "start", []);
    }
};

In the native code, there is a basic class that extends the PGPlugin class.  When the user invokes the “start()” function in JavaScript, the native “start” function will be invoked.   In this function, output is appended to the console using NSLog, and a NSTimer instance is started.   Once the timer is started, a success callback will be sent back to the HTML/JavaScript layer.

Now, the timer is executing indefinitely in the native code.   You will notice that in the timer handler “onTick” function, a message is written to the console, and a JavaScript string is created and routed to the UI layer using writeJavascript.   In this case, the JavaScript string just contains the current date as a string, to maintain simplicity.

#import "SamplePlugin.h"

@implementation SamplePlugin

- (void) start:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {

    NSString* callbackID = [arguments pop];
    NSLog(@"start invoked");

    [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self
                                   selector:@selector(onTick:)
                                   userInfo:nil
                                    repeats:YES];

    PluginResult* pluginResult = [PluginResult resultWithStatus:PGCommandStatus_OK messageAsString: @"OK"];
    [self writeJavascript: [pluginResult toSuccessCallbackString:callbackID]];
}

-(void)onTick:(NSTimer *)timer {

    NSLog(@"timer tick!");

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    NSString *js = [NSString stringWithFormat:@"updateContent( '%@' );", dateString];

    [self writeJavascript:js];
}

@end

When the native-generated JavaScript is executed, it will invoke the updateContent() JavaScript function, which will then update the HTML user interface.

While this example is extremely basic, you could use this exact same approach to push more complex data to the UI layer in real time.  This data could be coming from network activity, Bluetooth connections, or physical devices that are connected to the mobile device.

You can download the full source code for this sample project directly from: PhoneGapPluginDataPush.zip


PhoneGap Native Plugins

Posted: March 1st, 2012 | Author: | Filed under: Android, iOS, JavaScript, Mobile, open source, PhoneGap | Tags: , , , , , , | 4 Comments »

UPDATE:

In PhoneGap 1.5, the naming conventions were changed to use the Apache Cordova naming conventions.   EX: PGPlugin is now CDVPlugin, phonegap.js is now cordova.js, etc…   If you are running into issues, please be sure to check the PhoneGap version and appropriate naming conventions.

ORIGINAL POST:

Last night I attended a great Baltimore JavaScript Users Group meetup to engage with the community and to speak about PhoneGap native plugins. Many thanks to @bmorejs for having me, and great job to my fellow presenters Mike Wolf, who presented “PhoneGap: Blood and Guts” and Mike McKay, who presented on PhoneGap + CouchDB.

As promised, here are my slides, and I’ll also try to provide a bit more detail since there isn’t much of an explanation within the slide content: PhoneGap Native Plugins.pdf

PhoneGap Native Plugins Presentation

Here’s a brief synopsis of my presentation…

PhoneGap allows you to create natively installed mobile applications using web technologies (HTML, JS, CSS).  PhoneGap provides an API that lets you access capabilities of the native device/underlying operating system.  “Out of the box”, PhoneGap provides APIs for Accelerometer, Camera, Compass, Media, FileSystem, etc…  (You can get more info about the PhoneGap API from docs.phonegap.com.)

However, PhoneGap does not attempt to recreate every native API.   Luckily, if you need to access native functionality that isn’t already exposed, then you can easily create a native plugin to provide access to that native functionality.   For example, low latency audio processing, multi-screen iOS experiences, or anything else that has a native API.

PhoneGap native plugins shouldn’t be thought of as “plugins” like Flash Player inside of a browser, rather you are “plugging in” additional functionality that extends the core PhoneGap framework.   Even the PhoneGap core API itself is built upon this plugin model.  If you examine PhoneGap.plist in an iOS project, or phonegap.xml in an Android project, you can easily see the API mappings to native classes.

All PhoneGap plugins consist of a JavaScript class that exposes your functionality to your HTML/JS applications (red box in figure below).   The JavaScript class (green box in figure below) communicates to the native layer through the core PhoneGap class using PhoneGap.exec().  This invokes native functionality in your native plugin  (purple box in figure below).

Original image source: wiki.phonegap.com

You develop your JavaScript class to mirror the API of the native class.   In the JavaScript class, you invoke the native function using PhoneGap.exec, as shown below:

PhoneGap.exec(success, fail,   ”NameOfClassMapping”,   ”nameOfFunction", [params]);

Where “success” is a reference to a JavaScript function that will be invoked upon a “success” callback from the native code,  “fail” is a reference to a JavaScript function that will be invoked upon a “fail/error” callback from the native code, “NameOfClassMapping” is the plugin class reference (from phonegap.plist or phonegap.xml), “nameOfFunction” is the name of the native function that should be invoked, and [params] is an array of parameters to be passed into the native function.

In both Android and iOS, native plugin classes extend the PGPlugin class.

iOS

In iOS applications, this function is invoked directly, so invoking a function “myFunction” on the class “MyPlugin” is basically the same as calling the Objective C syntax:

[MyPlugin myFunction];

In iOS applications, you “return” a result to the web view using the writeJavascript method of the PGPlugin class, which invokes a JavaScript string inside of the web view. You create a PluginResult class instance, and write the JavaScript string back to the web view:

PluginResult* pluginResult = [PluginResult resultWithStatus:PGCommandStatus_OK messageAsString: @"OK"];
[self writeJavascript: [pluginResult toSuccessCallbackString:callbackID]];

You can also write native-code-generated JavaScript strings back to the PhoneGap web view using the writeJavaScript method – you can use this to “push” data or instructions to the web view at any time without being requested. An example of this is below:

NSString *js = [NSString stringWithFormat:@"myJSFunction( '%@' );" val];
[self writeJavascript:js];

In the web view, this would invoke the “myJSFunction” JavaScript function with the parameter in the “val” variable.

Android

In Android applications, functions are not invoked directly, instead, the “execute” method of the PGPlugin class in executed.  Inside of your class, you override the “execute” method, and determine the behavior based upon the “action” parameter, as shown below:

public PluginResult execute(String action,   JSONArray data, String callbackId){
  //do something based upon "action"
  if ( action.equals( "foo" ) ) {
     //handle the "foo" action
  }
  else if ( action.equals( "myFunction" ) ) {
     //handle the "myFunction" action
  }
  result = new PluginResult(Status.OK);
  return result;
}

When you return the PluginResult class at the end of this function, that PluginResult will be evaluated to call back to the success or error handler function.

You can also communicate back to the PhoneGap web view using the PGPlugin sendJavascript function to invoke custom JavaScript at any time, just as I described the iOS writeJavascript function above:

this.sendJavascript( myJavaScriptString )

It is important to understand that regardless of iOS, Android, or any other platform, communication between the web view JavaScript and the native code layer is not synchronous. Do not expect that your native code has executed in sequence after you have requested a native command. You need to use the success/error callback paradigm, and build your application logic using asynchronous coding practices.

Also keep in mind that writeJavascript or sendJavascript can be invoked at any time, not just after a method has been invoked by the JavaScript interface. Using sendJavascript and writeJavascript can enable you to “push” data to the web view. For example, let’s say you are monitoring a specific piece of hardware attached to a mobile device … perhaps a heart rate monitor. You could have a native heart rate monitor class that communicates with the device in a separate thread, and it pushes data back to the JavaScript layer in real time.

You can read more specifics about native plugins at http://wiki.phonegap.com

You can read more about the native plugin examples from last night’s presentation at the links below. Both are fully open source and free.

You can also browse the existing collection of open source native plugins at:

Update: You can also see a sample scenario for pushing data from a native plugin to the UI layer at:

Enjoy!


AIR 3.2 & Flash Player 11.2 Release Candidates Available on Adobe Labs

Posted: February 27th, 2012 | Author: | Filed under: ActionScript, Adobe, AIR, Android, Apps, Flash, iOS, Mobile | Tags: , , , , , , | No Comments »

AIR 3.2 and Flash Player 11.2 release candidates are now available for download on Adobe Labs. These latest versions have some exciting new features, including Stage3D for mobile devices, broader Stage3D support on desktop machines, multi-threaded video decoding, and better mouse support for gaming scenarios.   Get ready for some incredible mobile and desktop experiences powered by Adobe Flash & AIR.

You can read more about what’s new in Flash Player 11.2 and AIR 3.2 on the Adobe Digital Media blog, or check out the videos below to see some of the new features in action.

AIR 3.2

Flash Player 11.2

Download AIR 3.2 and Flash Player 11.2 release candidates today!

You can also check out additional examples of AIR 3.2 features from fellow Adobe Evangelists: