解析PhoneGap插件如何使用

移动开发
PhoneGap平台提供了插件功能,开发者可以将重量级的功能封装在原生代码开发的插件中,并将接口暴露给JavaScript,JavaScript在调用插件功能时都是非阻塞的,所以并不影响JavaScript层的性能。

PhoneGap插件如何使用是本文要介绍的内容,主要是来了解并学习PhoneGap插件的内容,PhoneGap是一个开源的开发框架,用来构建跨平台的使用HTML,CSS和JavaScript的移动应用程序,来看详细内容讲解。

一、PhoneGap平台

前不久PhoneGap发布了1.0版本,这为移动开发大家族提供了又一个跨平台的解决方案。开发者只要有JavaScript、CSS3、Html5的基础就可以快速开发移动应用,并且一次开发支持iOS、iOS(xcode 4)、Android、WebOS、Blackberry、Symbian 六大平台。

不过,JavaScript的速度虽然在近些年提高了100倍,其速度还是无法和原生代码相比。在编写复杂的业务逻辑时JavaScript显得力不从心。那么PhoneGap有没有办法解决这个问题呢?答案是肯定的。PhoneGap平台提供了插件功能,开发者可以将重量级的功能封装在原生代码开发的插件中,并将接口暴露给JavaScript,JavaScript在调用插件功能时都是非阻塞的,所以并不影响JavaScript层的性能。下面我们就看看如何编写和调用一个PhoneGap插件吧。

二、编写插件

由于要写原生代码,所以各个平台插件的编写略有不同。我们以Android为例吧。

1、插件功能

PhoneGap提供了文件读写的Api,但没有提供列出文件清单的功能。我们编写一个名为 DirectoryListingPlugin 的插件来实现列表SDCARD上文件的功能吧。

2、创建一个Android工程

如下图所示:

解析PhoneGap插件如何使用 

解析PhoneGap插件如何使用

3、包含PhoneGap依赖

下载PhoneGap并解压

在工程根目录新建目录/libs

拷贝 phonegap.jar 到 /libs

注:由于是写插件,所以只有phonegap.jar就够了。要建立完整的PhoneGap应用,可参考

  1. http://www.phonegap.com/start/#android  

4、实现插件类

解析PhoneGap插件如何使用

代码:

  1. /**    
  2.  * Example of Android PhoneGap Plugin    
  3.  */    
  4. package com.trial.phonegap.plugin.directorylisting;    
  5.  
  6. import java.io.File;    
  7.  
  8. import org.json.JSONArray;    
  9. import org.json.JSONException;    
  10. import org.json.JSONObject;    
  11.  
  12. import android.util.Log;    
  13.     
  14. import com.phonegap.api.Plugin;    
  15. import com.phonegap.api.PluginResult;    
  16. import com.phonegap.api.PluginResult.Status;    
  17.     
  18. /**    
  19.  * PhoneGap plugin which can be involved in following manner from javascript    
  20.  * <p>    
  21.  * result example -    
  22.  * {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt"    
  23.  * ,"isdir":false},{..}]}    
  24.  * </p>    
  25.  *     
  26.  * <pre>    
  27.  * {@code    
  28.  * successCallback = function(result){    
  29.  *     //result is a json    
  30.  *      
  31.  * }    
  32.  * failureCallback = function(error){    
  33.  *     //error is error message    
  34.  * }    
  35.  *     
  36.  * DirectoryListing.list("/sdcard",    
  37.  *        successCallback    
  38.  *        failureCallback);    
  39.  *                                     
  40.  * }    
  41.  * </pre>    
  42.  *     
  43.  * @author Rohit Ghatol    
  44.  *     
  45.  */    
  46. public class DirectoryListPlugin extends Plugin {    
  47.     /** List Action */    
  48.     public static final String ACTION = "list";    
  49.     
  50.     
  51.     /*    
  52.      * (non-Javadoc)    
  53.      *     
  54.      * @see com.phonegap.api.Plugin#execute(java.lang.String,    
  55.      * org.json.JSONArray, java.lang.String)    
  56.      */    
  57.     @Override    
  58.     public PluginResult execute(String action, JSONArray data, String callbackId) {    
  59.         Log.d("DirectoryListPlugin", "Plugin Called");    
  60.         PluginResult result = null;    
  61.         if (ACTION.equals(action)) {    
  62.             try {    
  63.                 String fileName = data.getString(0);    
  64.                 JSONObject fileInfo = getDirectoryListing(new File(fileName));    
  65.                 Log    
  66.                         .d("DirectoryListPlugin", "Returning "    
  67.                                 + fileInfo.toString());    
  68.                 result = new PluginResult(Status.OK, fileInfo);    
  69.             } catch (JSONException jsonEx) {    
  70.                 Log.d("DirectoryListPlugin", "Got JSON Exception "    
  71.                         + jsonEx.getMessage());    
  72.                 result = new PluginResult(Status.JSON_EXCEPTION);    
  73.             }    
  74.         } else {    
  75.             result = new PluginResult(Status.INVALID_ACTION);    
  76.             Log.d("DirectoryListPlugin", "Invalid action : " + action    
  77.                     + " passed");    
  78.         }    
  79.         return result;    
  80.     }    
  81.     
  82.     
  83.     /**    
  84.      * Gets the Directory listing for file, in JSON format    
  85.      *     
  86.      * @param file    
  87.      *            The file for which we want to do directory listing    
  88.      * @return JSONObject representation of directory list. e.g    
  89.      *         {"filename":"/sdcard"    
  90.      *         ,"isdir":true,"children":[{"filename":"a.txt"    
  91.      *         ,"isdir":false},{..}]}    
  92.      * @throws JSONException    
  93.      */    
  94.     private JSONObject getDirectoryListing(File file) throws JSONException {    
  95.         JSONObject fileInfo = new JSONObject();    
  96.         fileInfo.put("filename", file.getName());    
  97.         fileInfo.put("isdir", file.isDirectory());    
  98.         if (file.isDirectory()) {    
  99.             JSONArray children = new JSONArray();    
  100.             fileInfo.put("children", children);    
  101.             if (null != file.listFiles()) {    
  102.                 for (File child : file.listFiles()) {    
  103.                     children.put(getDirectoryListing(child));    
  104.                 }    
  105.             }    
  106.         }    
  107.         return fileInfo;    
  108.     }    
  109. }    
  110. /**  
  111.  * Example of Android PhoneGap Plugin  
  112.  */  
  113. package com.trial.phonegap.plugin.directorylisting;  
  114.  
  115. import java.io.File;  
  116.  
  117. import org.json.JSONArray;  
  118. import org.json.JSONException;  
  119. import org.json.JSONObject;  
  120.  
  121. import android.util.Log;  
  122.  
  123. import com.phonegap.api.Plugin;  
  124. import com.phonegap.api.PluginResult;  
  125. import com.phonegap.api.PluginResult.Status;  
  126.  
  127. /**  
  128.  * PhoneGap plugin which can be involved in following manner from javascript  
  129.  * <p> 
  130.  * result example -  
  131.  * {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt"  
  132.  * ,"isdir":false},{..}]}  
  133.  * </p> 
  134.  *   
  135.  * <pre> 
  136.  * {@code  
  137.  * successCallback = function(result){  
  138.  *     //result is a json  
  139.  *    
  140.  * }  
  141.  * failureCallback = function(error){  
  142.  *     //error is error message  
  143.  * }  
  144.  *   
  145.  * DirectoryListing.list("/sdcard",  
  146.  *     successCallback  
  147.  *     failureCallback);  
  148.  *                                   
  149.  * }  
  150.  * </pre> 
  151.  *   
  152.  * @author Rohit Ghatol  
  153.  *   
  154.  */  
  155. public class DirectoryListPlugin extends Plugin {  
  156.  /** List Action */  
  157.  public static final String ACTION = "list";  
  158.  
  159.  
  160.  /*  
  161.   * (non-Javadoc)  
  162.   *   
  163.   * @see com.phonegap.api.Plugin#execute(java.lang.String,  
  164.   * org.json.JSONArray, java.lang.String)  
  165.   */  
  166.  @Override  
  167.  public PluginResult execute(String action, JSONArray data, String callbackId) {  
  168.   Log.d("DirectoryListPlugin", "Plugin Called");  
  169.   PluginResult result = null;  
  170.   if (ACTION.equals(action)) {  
  171.    try {  
  172.     String fileName = data.getString(0);  
  173.     JSONObject fileInfo = getDirectoryListing(new File(fileName));  
  174.     Log  
  175.       .d("DirectoryListPlugin", "Returning "  
  176.         + fileInfo.toString());  
  177.     result = new PluginResult(Status.OK, fileInfo);  
  178.    } catch (JSONException jsonEx) {  
  179.     Log.d("DirectoryListPlugin", "Got JSON Exception "  
  180.       + jsonEx.getMessage());  
  181.     result = new PluginResult(Status.JSON_EXCEPTION);  
  182.    }  
  183.   } else {  
  184.    result = new PluginResult(Status.INVALID_ACTION);  
  185.    Log.d("DirectoryListPlugin", "Invalid action : " + action  
  186.      + " passed");  
  187.   }  
  188.   return result;  
  189.  }  
  190.  
  191.  
  192.  /**  
  193.   * Gets the Directory listing for file, in JSON format  
  194.   *   
  195.   * @param file  
  196.   *            The file for which we want to do directory listing  
  197.   * @return JSONObject representation of directory list. e.g  
  198.   *         {"filename":"/sdcard"  
  199.   *         ,"isdir":true,"children":[{"filename":"a.txt"  
  200.   *         ,"isdir":false},{..}]}  
  201.   * @throws JSONException  
  202.   */  
  203.  private JSONObject getDirectoryListing(File file) throws JSONException {  
  204.   JSONObject fileInfo = new JSONObject();  
  205.   fileInfo.put("filename", file.getName());  
  206.   fileInfo.put("isdir", file.isDirectory());  
  207.   if (file.isDirectory()) {  
  208.    JSONArray children = new JSONArray();  
  209.    fileInfo.put("children", children);  
  210.    if (null != file.listFiles()) {  
  211.     for (File child : file.listFiles()) {  
  212.      children.put(getDirectoryListing(child));  
  213.     }  
  214.    }  
  215.   }  
  216.   return fileInfo;  
  217.  }  

5、将插件类导出成jar 包

Eclipse中如下操作:

在要生成jar的项目上右击,选择菜单上的Export(导出)

导出类型选择Jar File

选择或者输入生成路径

选择要导出的类

我们导出成directorylist.jar

6、实现JavaScript插件

创建一个名为DirectoryListing的类

创建一个成员函数list()

在成员函数中调用

  1. PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin Name>>,<<Action Name>>,<<Arguments Array>>); 

将js文件保存为directorylisting.js

代码:

  1. /**   
  2.  *     
  3.  * @return Object literal singleton instance of DirectoryListing   
  4.  */    
  5. var DirectoryListing = {     
  6. /**   
  7.  * @param directory The directory for which we want the listing   
  8.  * @param successCallback The callback which will be called when directory listing is successful   
  9.  * @param failureCallback The callback which will be called when directory listing encouters an error   
  10.  */    
  11.     list: function(directory,successCallback, failureCallback) {    
  12.         return PhoneGap.exec(successCallback,        //Success callback from the plugin     
  13.                              failureCallback,        //Error callback from the plugin     
  14.                              'DirectoryListPlugin',  //Tell PhoneGap to run "DirectoryListingPlugin" Plugin     
  15.                              'list',                 //Tell plugin, which action we want to perform     
  16.                              [directory]);           //Passing list of args to the plugin     
  17.     }    
  18. };    
  19. /**  
  20.  *    
  21.  * @return Object literal singleton instance of DirectoryListing  
  22.  */  
  23. var DirectoryListing = {   
  24. /**  
  25.  * @param directory The directory for which we want the listing  
  26.  * @param successCallback The callback which will be called when directory listing is successful  
  27.  * @param failureCallback The callback which will be called when directory listing encouters an error  
  28.  */  
  29.     list: function(directory,successCallback, failureCallback) {  
  30.         return PhoneGap.exec(successCallback,        //Success callback from the plugin  
  31.                              failureCallback,        //Error callback from the plugin  
  32.                              'DirectoryListPlugin',  //Tell PhoneGap to run "DirectoryListingPlugin" Plugin  
  33.                              'list',                 //Tell plugin, which action we want to perform  
  34.                              [directory]);           //Passing list of args to the plugin  
  35.     }  
  36. }; 

三、测试

1.创建一个PhoneGap应用

2.将 directorylisting.jar 加入工程依赖

3.将directorylisting.js放入到 /assets/www 目录下。

4.在 /res/xml/plugins.xml 文件中添加 5、在index.html中调用DirectoryListing.list

代码:

  1. <!DOCTYPE HTML>    
  2. <html>    
  3.      <head>    
  4.           <title>PhoneGap</title>    
  5.      </head>    
  6.      <body>    
  7.           <!-- Button -->    
  8.           <input disabled id="list-sdcard" type="button" value="List SDCard Contents"   />    
  9.           <hr>    
  10.      
  11.           <!-- Place Holder for placing the SD Card Listing -->    
  12.           <div id="result"></div>    
  13.      
  14.           <hr>    
  15.      
  16.           <script type="text/javascript" src="phonegap-1.0.0.js"></script>    
  17.           <script type="text/javascript" src="directorylisting.js"></script>    
  18.           <script type="text/javascript" >    
  19.    document.addEventListener('deviceready', function() {    
  20.    var btn = document.getElementById("list-sdcard");    
  21.    btn.onclick = function() {    
  22.     DirectoryListing.list(    "/sdcard",    
  23. function(r){printResult(r)},    
  24. function(e){log(e)}    
  25. );    
  26.     }    
  27.     btn.disabled=false;    
  28.   }, true);    
  29.      
  30.      
  31.  function printResult(fileInfo){    
  32.   var innerHtmlText=getHtml(fileInfo);        
  33.   document.getElementById("result").innerHTML=innerHtmlText;    
  34.  }    
  35.      
  36.  function getHtml(fileInfo){    
  37.  var htmlText="<ul><li>"+fileInfo.filename;    
  38.  if(fileInfo.children){    
  39.      
  40.  for(var index=0;index<fileInfo.children.length;index++){    
  41.  htmlTexthtmlTexthtmlText=htmlText+getHtml(fileInfo.children[index]);    
  42.  }    
  43.  }    
  44.  htmlTexthtmlTexthtmlText=htmlText+"</li></ul>";    
  45.  return htmlText;    
  46.      
  47.  }     
  48.           </script>    
  49.      
  50.      </body>    
  51. </html>   

小结:解析PhoneGap插件如何使用的内容介绍完了,希望通过本文的学习能对你有所帮助!

责任编辑:zhaolei 来源: 互联网
相关推荐

2011-10-11 10:06:12

PhoneGap插件

2011-12-19 08:57:46

PhoneGapNativeContr

2011-09-05 14:26:43

PhoneGap插件

2011-12-23 10:02:37

PhoneGapAndroid插件

2011-09-02 13:38:56

PhoneGap插件Android

2012-03-07 11:17:19

AndroidPhoneGap插件

2011-09-02 15:12:29

PhoneGapSencha Touc

2011-09-01 10:01:35

PhoneGap应用程序GoodDay

2011-09-13 10:17:26

PhoneGap AP

2014-07-04 09:43:22

2011-09-13 11:06:08

PhoneGap AP

2011-09-13 10:40:25

PhoneGap AP

2011-09-13 14:07:45

PhoneGap AP

2022-07-29 07:36:01

虚拟机编程语言

2023-04-24 08:00:00

2010-08-03 10:46:41

Flex代码格式化

2011-09-13 13:36:17

PhoneGap

2012-05-17 08:29:54

PhoneGap误区

2019-02-26 13:00:11

JavaScriptURL前端

2021-08-11 22:50:53

JavaScript编程开发
点赞
收藏

51CTO技术栈公众号