Статьи

Расширение PhoneGap с помощью собственных плагинов

Прошлой ночью я посетил большое собрание пользователей JavaScript из Балтимора,  чтобы пообщаться с сообществом и рассказать о собственных плагинах PhoneGap . Большое спасибо @bmorejs за то, что приняли меня, и отличную работу моим коллегам-докладчикам Майку Вольфу , который представил « PhoneGap: Blood and Guts », и Майку Маккею , который представил на PhoneGap + CouchDB .

Как и было обещано, вот мои слайды, и я также постараюсь предоставить немного больше подробностей, поскольку в содержании слайдов нет большого объяснения:  PhoneGap Native Plugins.pdf

Презентация родных плагинов PhoneGap

Вот краткий обзор моей презентации …

PhoneGap позволяет создавать собственные мобильные приложения с использованием веб-технологий (HTML, JS, CSS). PhoneGap предоставляет API, который позволяет получить доступ к возможностям собственного устройства / базовой операционной системы. «Из коробки» PhoneGap предоставляет API-интерфейсы для акселерометра, камеры, компаса, мультимедиа, файловой системы и т. Д.   (Более подробную информацию об API PhoneGap можно получить на docs.phonegap.com .)

Однако PhoneGap не пытается воссоздать каждый нативный API. К счастью, если вам нужен доступ к нативным функциям, которые еще не представлены, вы можете легко создать собственный плагин для предоставления доступа к этим нативным функциям. Например, обработка аудио с малой задержкой , многоэкранный интерфейс iOS или все, что имеет собственный API.

Родные плагины PhoneGap не следует рассматривать как «плагины», такие как Flash Player внутри браузера, скорее вы «подключаете» дополнительную функциональность, расширяющую базовую платформу PhoneGap. Даже основной API PhoneGap построен на этой модели плагинов. Если вы изучите PhoneGap.plist в проекте iOS или phonegap.xml в проекте Android, вы сможете легко увидеть сопоставления API с нативными классами.

Все плагины PhoneGap состоят из класса JavaScript, который предоставляет ваши функциональные возможности вашим приложениям HTML / JS (красная рамка на рисунке ниже). Класс JavaScript (зеленое поле на рисунке ниже) связывается с собственным уровнем через основной класс PhoneGap с помощью PhoneGap.exec (). Это вызывает нативную функциональность в вашем родном плагине (фиолетовая рамка на рисунке ниже).

Исходный источник изображения:  wiki.phonegap.com

Вы разрабатываете свой класс JavaScript для отражения API нативного класса. В классе JavaScript вы вызываете встроенную функцию с помощью PhoneGap.exec, как показано ниже:

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!